Given a string S, find the longest palindromic substring in s. The maximum length of S is assume, and there exists one unique longest palindromic substring.
Solution One: Consider the characteristics of palindrome string palistr, divided into the string length is odd even two cases: (1) palistr.size () is odd, then from the middle of a character to both sides of the extension is symmetrical, such as ABCDCBA; (2) Palistr.size () is odd , it is symmetrical to extend from the most intermediate two characters to both sides, such as ABCCBA. So you can get the following ideas: (1) Initialize the longest palindrome substring length maxlen=0, the longest palindrome substring length curmax=1, the longest palindrome substring lstpali= ""; (2) (odd case processing) from I=1 to I=str.size ()-2 traversing through the input string, With the current character as the center, to the left and right symmetry extension, if the symmetric position character is consistent, then curmax+=2, and then continue to expand to the left and right until the end of the string, or if Maxlen<curmax, set Maxlen=curmax, and update Lstpali ; (3) (even case processing) set the current longest palindrome substring length curmax=2, from i=0 to I=str.size ()-2 traversing through the input string, if the first and second characters and the i+1 characters are the same, then they are centered toward the left and right symmetry extension, if the symmetric position character is consistent, The curmax+=2, then continues to expand to the left and right until it reaches the end of the string, otherwise if Maxlen<curmax, the Maxlen=curmax is set and the Lstpali is updated. The time complexity is O (n*n).
classSolution { Public: stringLongestpalindrome (strings) {intSS =s.size (); if(SS <2) returns; if(ss = =2)(S[0] = = S[1])?returnS:return string(S.begin (), S.begin () +1); intMaxLen =0; stringRes; intLeft , right; for(inti =1; I < SS; i++) { left= right =i; intCurmax =1; Curmax+=Findlstpali (S, left, right); if(Curmax >maxlen) {MaxLen=Curmax; stringTMP (S.begin () + left, S.begin () + Right +1); Res=tmp; } } for(inti =0; I < SS-1; i++) { if(S[i] = = S[i +1]) { left=i; Right= i +1; intCurmax =2; Curmax+=Findlstpali (S, left, right); if(Curmax >maxlen) {MaxLen=Curmax; stringTMP (S.begin () + left, S.begin () + Right +1); Res=tmp; } } } returnRes; } Private: intFindlstpali (string& STR,int& Left,int&Right ) { intSS =str.size (); intLen =0; while(true) { --Left ; ++Right ; if(Left >=0&& Right <SS) { if(Str[left] = =Str[right]) Len+=2; Else Break; } Else Break; } ++left; --right; returnLen; }};
Solution Two: Use the dynamic programming method.
[Leetcode]33. Longest palindromic substring longest palindrome substring