回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。
输入一个字符串Str,输出Str里最长回文子串的长度。
Input
输入Str(Str的长度 <= 1000)
Output
输出最长回文子串的长度L。
Input示例
daabaac
Output示例
5
#include <cstdio> #include <iostream> #include <cstring> using namespace std; char str[1000002 + 1200]; int fast(char *p) { int ans = 1; for (int i = 1; p[i]; ++i) { int s = i, e = i, t; while(p[e+1] == p[i]) { ++e; } i = e; while(p[s-1] == p[e+1]) { --s; ++e; } if((t = e-s+1) > ans) { ans = t; } } return ans; } int main() { str[0] = '$'; while (cin>>(str+1)) { cout<<fast(str)<<endl; } return 0; }
#include <iostream> #include <cstring> using namespace std; int main() { char s[1005], t[2010]; memset(t, 0, sizeof(t)); cin>>s; int length = strlen(s); int k = 0; t[0] = '#'; for(int i = 1; i <= 2*length - 1; i+=2) { t[i] = s[k++]; t[i+1] = '#'; } int l, r, temp, max = 0; for(int i = 0; i <= 2*length; i++) { l = r = i; if(l==0 || r==2*length) { temp = 1; } else { while(t[l]==t[r]) { l--; r++; } temp = r-l; } if(temp > max) { max = temp; } } cout<<(max-1)/2<<endl; return 0; }