POJ 2406题解kmp算法的应用

版权声明:转载请注明出处哦~ https://blog.csdn.net/Cassie_zkq/article/details/81665153

POJ2406传送门

题目意思:

比如给出一个字符串,让你找出它是由多少个相同子串组成的,输出该子串的最大个数

比如abababab,它是由子串ab重复4次组成的,输出4

abcd它是由子串abcd重复1次组成的,输出1

注:我所用的next数组下标都是从1开始的,字符串数组也是从1开始读取的

 

i 1 2 3 4 5 6 7 8 9
字符 a b a b a b a b  
next[i] 0 1 1 2 3 4 5 6 7

所以答案就是8/(9-7)=4

ac代码:

#include <iostream>
#include <cstring>
#define maxn 1000005
using namespace std;
char s[maxn];
int len;
int nnext[maxn];
void getnext()
{
    nnext[1]=0;
    int j=1,k=0;
    while(j<=len)
    {
        if(k==0||s[j]==s[k])
        {
            k++;
            j++;
            nnext[j]=k;
        }
        else k=nnext[k];
    }
}
int main()
{
    while(scanf("%s",s+1)!=EOF&& s[1]!='.')
    {
        if(s[1]=='.') break;
        int ans=0;
        len=strlen(s+1);
        getnext();
        ans=len/(len+1-nnext[len+1]);
        if(len%(len+1-nnext[len+1])==0)
            printf("%d\n",ans);
        else puts("1");

    }
    return 0;
}

有一个小细节需要注意下,while的条件中要写成&& s[1]!='.'    注意中间要有一个空格

或者写成

   while(scanf("%s",s+1)!=EOF)
    {
        if(s[1]=='.') break;

如果写成

while(scanf("%s",s+1)!=EOF&&s[1]!='.')

那么遇到.就不会结束while

猜你喜欢

转载自blog.csdn.net/Cassie_zkq/article/details/81665153