0% found this document useful (0 votes)
14 views2 pages

Longest Plaindrom From The Sequence of String

Uploaded by

HASMUKH RUSHABH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

Longest Plaindrom From The Sequence of String

Uploaded by

HASMUKH RUSHABH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

/*

input = "amadambba"

ouput = "madam" is the solution

the brute force appraoch says that if the given string is there then take pointers
and then check every single
value of the string and check the palindrome it takes O(n^2) time compliexity

one optimal solution is that take two pointers from left and right
and store that value in the matrix , the major benfit is that when you check the
value of palindrome of largest string and that string is
already is store in the matrix so that the time complexity is already reduce

hinit is that add that value in matrix until and take two pointers from that we can
higest value

example : aabaa
matrix is that

a a b a a
a 1 2 0 0 5 <= longest palindrom
a 1 0 3 0
b 1 0 0
a 1 2
a 1

// vector is used for extenable array we can grow size or shrank like linked list

class solution {
public string longestPalindrome (String s) {
int len = s.length();
int maxlen = 0;
string ans; // this is used for storeing the final value of
longest palaindrome from the string

/* vector<vector> is used to store 2d matrix of integer "<int>"


dp is used to store the data in varaiable
(n,vector<int>(n,0)); is used in which dimenions is store that
matrix and vector<int>(n,0) is for inner matrix meanms 2nd for loop
amd 0 => indicates that instailzeition of matrix is 0;
*/

vector<vector<int>> dp (n,vector<int>(n,0);

// using two for loop we can alternate the matrix in diagonal


for (int diff = 0 ; diff < len ; diff++){
for (int i= 0 ; j = i + diff ; j < len; i++ ; j++){
if(i == j){
dp[i][j] = 1;
}
else if(diff == 1){

}
}
}
}
}

*/

public class Solution {


private int lo, maxLen;

public String longestPalindrome(String s) {


int len = s.length();
if (len < 2)
return s;

for (int i = 0; i < len-1; i++) {


extendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as
possible
extendPalindrome(s, i, i+1); //assume even length.
}
return s.substring(lo, lo + maxLen);
}

private void extendPalindrome(String s, int j, int k) {


while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
j--;
k++;
}
if (maxLen < k - j - 1) {
lo = j + 1;
maxLen = k - j - 1;
}
}
}

You might also like