POJ2406--Power Strings

题目在这儿。

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue> 
using namespace std;
int next[1000001];
char s[1000001];
void gt(){
    int i=0,j=-1;
    next[0]=-1;
    int len=strlen(s);
    while(i<len){
        if(s[i]==s[j]||j==-1){
            i++;
            j++;
            next[i]=j;
        }
        else
            j=next[j];
    }
}
int main(){
    while(scanf("%s",s)>0){
        if(s[0]=='.'){
            break;
        } 
        int len=strlen(s);
        gt();
        if(len%(len-next[len])==0){ 
            printf("%d\n",len/(len-next[len]));
        } 
        else{ 
            printf("1\n");
        } 
    }
    return 0;
}

字符串当然要有KMP算法写。

next表示模式串如果第i位(设str[0]为第0位)与文本串第j位不匹配则要回到第next[i]位继续与文本串第j位匹配。

猜你喜欢

转载自www.cnblogs.com/xiongchongwen/p/11135453.html
今日推荐