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.
Analysis:
This problem is similar to longest Valid parentheses, except that Valid parentheses each extension is two characters, and Palindrome can expand one character at a time. In the dynamic programming algorithm, valid parentheses can make a memo with a one-dimensional array, and palindrome needs a two-dimensional array. The subject is sometimes complex O (n), spatial complexity O (n) algorithm, see Leetcode.pdf Page65 's Manacher ' s algorithm. The dynamic programming method used here is O (n^2) for both time complexity and space complexity, but the data structure with vector is timed out. The code is as follows:
classSolution { Public: stringLongestpalindrome (strings) {intn =s.length (); if(n = =0)return ""; BOOLf[ +][ +]; intStart =0, Max_len =0; for(intj =0; J < N; J + +) for(inti =0; I <= J; i++){ if(i = = J | | j-i >1&& f[i+1][j-1] && s[i] = = S[j] | | i +1= = J && s[i] = =S[j]) {F[i][j]=true; if(J-i +1>Max_len) {Max_len= J-i +1; Start=i; } }ElseF[I][J] =false; } returns.substr (Start, Max_len); }};
Leetcode:longest palindromic Substring