Longest palindrome substring:
1. Brute force search Time Complexity O (n^3)
2. Dynamic planning
- DP[I][J] Indicates whether the substring S[I...J] is a palindrome
- Initialize: Dp[i][i] = True (0 <= i <= n-1); Dp[i][i-1] = True (1 <= i <= n-1); The rest is initialized to false
- DP[I][J] = (s[i] = = S[j] && dp[i+1][j-1] = = True)
Time complexity O (n^2), Space O (n^2)
3. With an element as the center, the maximum length of palindrome with even length and the maximum length of odd length palindrome are calculated respectively. Time complexity O (n^2), Space O (1)
4. Manacher algorithm, time complexity O (n), spatial complexity O (n). Refer to the following links for details:
Http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
classSolution { Public: stringLongestpalindrome (strings) {intn =2*s.length () +3; CharCstr[n]; cstr[0] ='\1'; Cstr[n-1] =' /'; for(inti =1; I < n; i + =2) Cstr[i]='#'; for(inti =2; I < n; i + =2) Cstr[i]= s[i/2-1]; int*p; P=New int[n]; Memset (P,0,sizeof(int)*N); intmx, id, I, J; for(id =1, i =2, mx =0; I < n; ++i) {j=2*id-i; P[i]= (mx > i)? Min (P[j], mx-i):0; while(Cstr[i + p[i] +1] = = Cstr[i-(P[i] +1)]) ++P[i]; if(i + p[i] >MX) {ID=i; MX= ID +P[id]; } } intmax =-1; for(i =2; I < n2; ++i) {if(Max <P[i]) {Max=P[i]; ID=i; } } returnS.substr (Id-max-1)/2, Max); }Private:};
Leetcode problem (5)