码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-11-03 12:46:45      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:while   ble   next数组   poj2406   const   problem   print   std   nbsp   

题目链接: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;
}

 

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

标签:while   ble   next数组   poj2406   const   problem   print   std   nbsp   

原文地址:https://www.cnblogs.com/FrankChen831X/p/11785495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!