POJ2406:Power Strings

题目描述


大概意思是输入字符串,判断该字符串是不是由循环子串组成的,是的话输出由几个循环字串组成,不是的话输出1

题目分析

  • 正好刚复习了KMP,看题解发现可以用next数组直接求
  • 如果由循环子串组成的话,next[len]的值一定是第一个循环子串尾到字符串尾的距离
  • 没想到strlen()把我卡TLE了

代码

#include <stdio.h>
#include<string.h>
const int N=1000001;
char pat[N];
int next[N];
int len;
void getNext(char *p){
    int i=0,j=-1;
    next[0]=-1;
    while(i<len){
        if(j==-1||p[i]==p[j]){
            i++,j++;
            next[i]=j;
        }else{
            j=next[j];
        }
    }
}
int main() {
    freopen("in.txt","r",stdin);
    while(scanf("%s",pat)!=EOF){
        if(pat[0]=='.'){
            break;
        }
        len=strlen(pat);
        getNext(pat);
        if(len%(len-next[len])==0){
            printf("%d\n",len/(len-next[len]));
        }else{
            printf("1\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/armstrong_rose/article/details/80766067