输出最长回文串字符数

xiaoxiao2021-02-27  374

/* 复杂度O(n2)的简洁求法 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; } */ #include <bits/stdc++.h>using namespace std;int ans[1000*2];string change(string a){ string b; b+='$'; b+='#'; for(int i=0;i<a.size();i++) { b+=a[i]; b+='#'; } return b;}void huiwen(string a){ int maxans=-1; int maxid=0; int id=0; memset(ans,0,sizeof(a)); string b=change(a); for(int i=0;i<b.size();i++) { if(maxid>i) { maxid=ans[id*2-i]<maxid-i?ans[id*2-i]:maxid-i; } else { ans[i]=1; } while(b[i+ans[i]]==b[i-ans[i]])ans[i]++; if(ans[i]+i>maxid) { maxid=ans[i]+i; id=i; } if(maxans<ans[i]) maxans=ans[i]; } cout<<maxans-1<<endl;}int main(){ string a; while(cin>>a) { huiwen(a); } return 0;}
转载请注明原文地址: https://www.6miu.com/read-4789.html

最新回复(0)