The original question is as follows:
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.
If you select any substring, calculate whether the substring is intertextuality, and then take the largest substring, with a time complexity of O (n*n*n) =o (n^3), this must not be tested.
Another method is to select a character, centered on the character, and expand to the left and right, respectively, to calculate the maximum cross-text string centered on this character. Note, of course, that if the substring length is even, it will be two characters in the center. The worst time complexity for this method is O (2*n*n) =o (n^2). The worst case scenario occurs when the string is the same character, and can be optimized so that the complexity of the time can be further reduced. See the following code for the specific algorithm:
1 Publicstring Longestpalindrome (string s) {2 if(S.length () < 2) {3 returns;4 }5 intMaxLen = 1;6 intMaxi = 0;7 intMAXJ = 1;8 for(inti = 1; I < s.length ()-maxlen/2-1; i++) {9 if(S.charat (i) = = S.charat (i + 1) | | S.charat (i) = = S.charat (i-1)) {Ten Continue; One } A intj = 1; - for(; i-j >= 0 && i + J < s.length () && s.charat (i-j) = = S.charat (i + j); J + +); - intLen =--j * 2 + 1; the if(Len >maxlen) { -MaxLen =Len; -Maxi = i-J; -MAXJ = i + j + 1; + } - } + for(inti = 0; I < s.length ()-MAXLEN/2;) { A intj =i; at for(; j + 1 < s.length () && S.charat (j) = = S.charat (j + 1); J + +); - if(I! =j) { - intII = i, JJ =J; - while(ii >= 0 && JJ < s.length () && S.charat (ii) = =S.charat (JJ)) { -ii--; -jj++; in } -ii++; tojj--; + intLen = jj-ii+1; - if(Len >maxlen) { theMaxLen =Len; *Maxi =II; $MAXJ = JJ + 1;Panax Notoginseng } - } thei = j + 1; + } A returns.substring (Maxi, MAXJ); the}
Reference Source: https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/ Longestpalindromicsubstring5.java
Leetcode 5-longest palindromic Substring