1.manachar 马拉车 算法
-------求最长回文串
时间复杂度为 O(n)
int Init() //此操作目的是消除奇偶性 { int len=strlen(s); s[0]='@'; s[1]='#'; int j=2; for(int i=0;i<len;i++) { s[j++]=s[i]; s[j++]='#'; } s[j]=' '; return j; //返回修改后的长度 } int manachar() { int len=Init(); int ans=-1;int p=0; int maxlen=0; for(int i=1;i<len;i++) { if(i<maxlen)r[i]=min(r[2*p-i],maxlen-i+1); else r[i]=1; while (s[i-r[i]]==s[i+r[i]])r[i]++; if(maxlen<i+r[i]-1) { p=i; maxlen=i+r[i]-1; } ans=max(ans,r[i]-1); } return ans; }
2. kmp!
void kmp() { fail[1]=j=0; for(int i=2;i<=m;i++) { while (j&&a[j+1]!=b[i])j=fail[i]; if(fail[j+1]==fail[i])j++; fail[i]=j; } j=0; for(int i=1;i<=n;i++) { while(j&&b[j+1]!=fa[i])j=fail[j]; if(b[j+1]==a[i])j++; if(j==m) { cout<<"match:"<<i-m+1<<endl; j=fail[j]; } } }
3.hash
bool mark[524288]; unsigned int checkhash(string str) { unsigned int seed=131; unsigned int hash =0,i=0;len=sre.length(); while(i<len)hash=hash*seed+str[i++]; return (hash&0x7FFFF); }
4.最小表示法
cin>>s; l=s.length(); s=s+s; i=0,j=1; while(i<l&&j<l) { for(k=0;k<l;k++) if(s[i+k]!=s[j+k])break; if(k==l)break; if(s[i+k]>s[j+k])i+=k+1; else if(s[i+k]<s[j+k])j+=k+1; if(i==j)j++; } cout<<min(i,j)<<endl;