回文的含义是:正看和倒看相同,如abba和yyxyy
http://blog.163.com/zhaohai_1988/blog/static/2095100852012716105847112/
http://www.cnblogs.com/en-heng/p/3973679.html
http://blog.csdn.net/feliciafay/article/details/16984031
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的每一个子串,去判断这个子串是不是回文,是回文的话看看长度是不是比最大的长度maxlength大。遍历每一个子串的方法要O(N2),判断每一个子串是不是回文的时间复杂度是O(N),所以暴利方法的总时间复杂度是O(N3)。
算法
动态规划
动态规划就是暴力法的进化版本,我们没有必要对每一个子串都重新计算,看看它是不是回文。我们可以记录一些我们需要的东西,就可以在O(1)的时间判断出该子串是不是一个回文。这样就比暴力法节省了O(N)的时间复杂度哦,嘿嘿,其实优化很简单吧。
有母串s,我们用c[i, j] = 1表示子串s[i..j]为回文子串,那么就有递推式
c[i,j]=c[i+1,j−1]
………
if
……
s[i]=s[j]
c[i,j]=0
………..
if
……
s[i]≠s[j]
递推式表示在s[i] = s[j]情况下,如果s[i+1..j-1]是回文子串,则s[i..j]也是回文子串;如果s[i+1..j-1]不是回文子串,则s[i..j]也不是回文子串。
初始状态:
- c[i][i]=1
- c[i][i+1]=1 ……. if ….. s[i]=s[i+1]
上述式子表示单个字符、两个字符均是回文串。
class Solution {
public:
string longestPalindrome(string s) {
int n=s.length();
int longestBegin=0;
int maxlen=1;
bool table[1000][1000]={false};
for(int i=0;i<n;i++){
table[i][i]=true;
}
for(int i=0;i<n-1;i++){
if(s[i]==s[i+1]){
table[i][i+1]=true;
longestBegin=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] && table[i+1][j-1]){
table[i][j]=true;
longestBegin=i;
maxlen=len;
}
}
}
return s.substr(longestBegin,maxlen);
}
};
http://www.cnblogs.com/biyeymyhjob/archive/2012/10/04/2711527.html
http://articles.leetcode.com/longest-palindromic-substring-part-ii
https://www.felix021.com/blog/read.php?2040
http://www.open-open.com/lib/view/open1419150233417.html
算法: manacher
class Solution {
public:
string preProcess(string s) {
int n = s.length();
if (n == 0) return "^$";
string ret = "^";
for (int i = 0; i < n; i++)
ret += "#" + s.substr(i, 1);
ret += "#$";
return ret;
}
string longestPalindrome(string s) {
string T = preProcess(s);
int n = T.length();
int *P = new int[n];
int C = 0, R = 0;
for (int i = 1; i < n-1; i++) {
int i_mirror = 2*C-i; // equals to i' = C - (i-C)
P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0;
// Attempt to expand palindrome centered at i
while (T[i + 1 + P[i]] == T[i - 1 - P[i]])
P[i]++;
// If palindrome centered at i expand past R,
// adjust center based on expanded palindrome.
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
// Find the maximum element in P.
int maxLen = 0;
int centerIndex = 0;
for (int i = 1; i < n-1; i++) {
if (P[i] > maxLen) {
maxLen = P[i];
centerIndex = i;
}
}
delete[] P;
return s.substr((centerIndex - 1 - maxLen)/2, maxLen);
}
};