Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
题目的意思:输入一个字符串S,找出其最长回文串
用动态规划求解
决策变量:dp[i][j]记录从s[i]到s[j]组成的子串是否为回文。
dp[i+1][j-1] , 当s[i]与s[j]相等时
dp[i][j] =
false , 当s[i]与s[j]不相等时
单个字符是回文串,故要初始化对角线
紧邻的两个相同字符也是回文
时间复杂度O(n^2)
class Solution { public: string longestPalindrome(string s) { int n = s.length(), startIndex = 0, maxLen = 1; // vector<vector<bool> > dp(n,vector<bool>(n,false)); bool dp[1000][1000] = {false}; for(int i = 0 ; i < n; ++ i) dp[i][i] = true; for(int i = 0; i < n-1; ++ i ){ if(s[i] == s[i+1]){ dp[i][i+1] = true; startIndex= i; maxLen = 2; } } for(int len = 3; len <= n; ++len){ for(int i = 0 ; i < n-len+1; ++ i){ int j = i+len-1; if(s[i] == s[j] && dp[i+1][j-1]){ dp[i][j] = true; startIndex =i; maxLen = len; } } } return s.substr(startIndex,maxLen); } };
利用Manacher 算法求解,时间复杂度为O(n)
可以参考http://www.felix021.com/blog/read.php?2040
和http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
string preProcess(string s){ int n = s.length(); if( n == 0) return "^$"; string res="^"; for(int i = 0 ; i < n; ++ i) res+="#"+string(1,s[i]); res+="#$"; return res; } string longestPalindrome(string s){ string T = preProcess(s); int n = T.length(); vector<int> p(n,0); int center = 0, radius = 0,maxv = 0; for(int i = 1; i < n-1; ++ i){ p[i] = (radius > i) ? min(radius-i,p[2*center-i]) : 0; while(T[i+1+p[i]] == T[i-1-p[i]]) p[i]++; if(i+p[i] > radius){ center = i; radius = i+p[i]; } } int maxLen = 0, centerIndex = 0; for(int i = 1; i < n-1; ++ i){ if(p[i] > maxLen){ maxLen = p[i]; centerIndex = i; } } centerIndex = (centerIndex - 1-maxLen)/2; return s.substr(centerIndex,maxLen); }