Link: http://tioj.ck.tp.edu.tw/problems/1206
把題目給的字串反轉,做z value(z algorithm)即可
如果第i個字元(0-based)的z value( z[i] )>=i 就代表那是一個可能的密碼,取最大值就是答案了
複雜度: O(n)
AC code| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 
 | #include <iostream>#include <algorithm>
 using namespace std;
 int z[200010];
 int main()
 {
 ios::sync_with_stdio(0);
 cin.tie(0);
 
 string s;
 while(cin>>s)
 {
 reverse(s.begin(),s.end());
 z[0]=-1;
 int r=0,rf=0;
 for(int i=1;i<(int)s.size();i++)
 {
 int j=i;
 if(r>i) j=min(i+z[i-rf],r);
 for(; j<(int)s.size()&&s[j]==s[j-i]; j++);
 z[i]=j-i;
 if(j-1>r){r=j-1; rf=i;}
 
 }
 int ans=0;
 for(int i=0;i<(int)s.size();i++)
 if(z[i]>=i)
 ans=max(ans,i);
 cout<<ans<<endl;
 }
 }
 
 |