poj 2406:Power Strings

給定一個字符串,求這個字符串最多由一個字符串重複幾次構成。


就是求最小重複字串。想到了用kmp的next數組做,但沒想到是用最後的i失配時回退的位置來做的。


代碼:

//Memory: 5100K		Time: 125MS
//Language: C++		Result: Accepted

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int maxn=1000005;
char s[maxn];
int next[maxn];

int getnext(){
    int i=-1,j=0,len=strlen(s);
    next[0]=-1;
    while(j<len){
        if(i==-1 || s[i]==s[j]){
            if(s[++i]==s[++j]) next[j]=next[i];
            else next[j]=i;
        }
        else i=next[i];
    }
    int len_ans=len-i;
    if(len%len_ans==0) return len/len_ans;
    else return 1;
}

int main(){
    //freopen("in.txt","r",stdin);
    while(~scanf("%s",s)){
        if(strcmp(s,".")==0) break;

        memset(next,0,sizeof(next));
        cout<<getnext()<<endl;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章