# 求解最大回文字符串长度 — 三种算法

``````int findLongestPalindrome(string &s) {
const int length = s.size();
int maxlength = 0;

// 长度为奇数
for (int i=0; i<length; i++) {
int j=i-1, k=i+1;
while (j>=0 && k<length && s.at(j)==s.at(k)) {
if(k-j+1 > maxlength)
maxlength = k-j+1;
j--;
k++;
}
}

// 长度为偶数
for (int i=0; i<length; i++) {
int j=i, k=i+1;
while (j>=0 && k<length && s.at(j)==s.at(k)) {
if(k-j+1 > maxlength)
maxlength = k-j+1;
j--;
k++;
}
}

return maxlength;
}``````

Manacher

``````int Manacher(char *st,int len)
{
int mx=0, ans=0, po=0;
for (int i=1; i<=len; i++) {
if (mx > i)
Len[i] = min(mx-i, Len[2*po-i]);
else
Len[i] = 1;
while (st[i-Len[i]] == st[i+Len[i]])
Len[i]++;
if (Len[i]+i > mx) {
mx = Len[i]+i;
po = i;
}
ans = max(ans, Len[i]);
}
return ans-1;
}``````

``````public int longestPalindrome(String s) {
int n=s.length();
boolean[][] pal=new boolean[n][n];
//pal[i][j] 表示s[i...j]是否是回文串
int maxLen=0;
for (int i=0;i<n;i++){  // i作为终点
int j=i;    //j作为起点
while (j>=0){
if (s.charAt(j)==s.charAt(i)&&(i-j<2||pal[j+1][i-1])){
pal[j][i]=true;
maxLen=Math.max(maxLen, i-j+1);
}
j--;
}
}
return maxLen;
}``````