Given the string S, find the longest input string in its substring.
Inversion Method: If S is reversed, find the longest common substring S, and check whether the subscript of S in S is satisfied with the subscript is in S: length (S) = is + is '+ Length (s ). if yes, S is the search result. If not, we will continue searching.
DP Solution: Define P [I] [J] = true <-> Si... SJ is the input string, otherwise false; P [I + 1] [J-1] = true & Si = SJ <-> P [I] [J] = true; basically, P [I] [I] = true and P [I] [I + 1] = (SI = Si + 1) so that we can construct and search within the Square time, and use the square space.
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 if (s.length() <= 1) return s; 5 // DP solution 6 bool P[1000][1000] = {false}; 7 int start = 0; 8 int maxLen = 0; 9 for (int i = 0; i < s.length(); i++) {10 P[i][i] = true;11 }12 for (int i = 0; i < s.length() - 1; i++) {13 if (s[i] == s[i+1]) {14 P[i][i+1] = true;15 start = i;16 maxLen = 2;17 }18 }19 for (int len = 3; len <= s.length(); len++) {20 for (int i = 0; i < s.length() - len + 1; i++) {21 int j = i + len - 1;22 if (s[j] == s[i] && P[i+1][j-1]) {23 P[i][j] = true;24 start = i;25 maxLen = len;26 }27 }28 }29 return s.substr(start, maxLen);30 }31 };Center Method: A back-to-text is always centered on a specific character. The center contains 2n-1 (including "blank" in the middle of 2 characters "). considering that expansion from the center requires O (n) times, the total time complexity is O (n2 ).
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 if (s.length() <= 1) return s; 5 string longest = s.substr(0, 1); 6 // Center Solution 7 for (int i = 0; i < s.length() - 1; i++) { 8 string res = expandFromCenter(s, i, i); 9 if (res.length() > longest.length()) longest = res;10 res = expandFromCenter(s, i, i+1);11 if (res.length() > longest.length()) longest = res;12 }13 return longest;14 }15 16 string expandFromCenter(string s, int l, int r) {17 while (l >= 0 && r < s.length() && s[l] == s[r]) {18 l--;19 r++;20 }21 return s.substr(l+1, r-l-1);22 }23 };
Manacher method: Linear Time solution, complex, and timestamp.
[Leetcode series] Longest reply string Problem