poj2406(求字符串的周期,kmp算法next数组的应用)

题目链接:https://vjudge.net/problem/POJ-2406

题意:求出给定字符串的周期,和poj1961类似。

思路:直接利用next数组的定义即可,当没有周期时,周期即为1。

AC代码:

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

const int maxn=1e6+5;
int n,nex[maxn],len;
char s[maxn];

void get_next(){
    int j;
    j=nex[0]=-1;
    for(int i=1;i<len;++i){
        while(j>-1&&s[i]!=s[j+1]) j=nex[j];
        if(s[i]==s[j+1]) ++j;
        nex[i]=j;
    }
    int t1=len-1,t2=nex[t1];
    if((t1+1)%(t1-t2)==0&&(t1+1)/(t1-t2)>1)
        printf("%d\n",(t1+1)/(t1-t2));
    else
        printf("1\n");
}

int main(){
    while(scanf("%s",s),len=strlen(s),s[0]!='.'||len!=1)
        get_next();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/FrankChen831X/p/11785495.html
今日推荐