#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
//最长回文子串
//有字母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])
int longest(string str)
{
int len = str.length();
int c[100][100];
int i, j;
int longest = 1;
if (str.length() == 0)
return 0;
if (str.length() == 1)
return 1;
for (i = 0; i < len; i++)
{
c[i][i] = 1;
if (str[i] == str[i + 1])
c[i][i + 1] = 1;
}
for (i = 0; i < len; i++)
{
for (j = i + 2; j <= len; j++)
{
if (str[i] == str[j])
{
c[i][j] = c[i + 1][j - 1];
if (c[i][j])
{
int n = j - i + 1;
if (longest < n)
longest = n;
}
}
else
c[i][j] = 0;
}
}
return longest;
}
void main()
{
string str;
cin >> str;
cout << longest(str);
}
最长回文子串
最新推荐文章于 2020-05-21 13:56:16 发布