POJ 2406 Power Strings

题目描述:给出一个字符串s,求该字符串最多是由多少个重复字符串连接而成。

分析:KMP算法每次求得的next值就是当前到i为止的前子串与后字符串相等的子串的长度。

#include<cstdio>
#include<cstring>

int main()
{
    int i, j, len;
    char str[1000005];
    int next[1000005];

    while(scanf("%s",str) != EOF)
    {    
        if(strcmp(str, ".") == 0)
		break;

	len = strlen(str);
	next[0] = -1;
	i = 0; j = -1;
	while(i < len) //KMP算法next过程
	{
		if(j == -1 || str[i] == str[j])
		{
			i++; j++;
			next[i] = j;
		}
		else
		{
			j = next[j];
		}
	}

        len = strlen(str);
        if(len % (len - next[len]) == 0)
	{
            printf("%d\n", len / (len - next[len]));
	}
        else
	{
            printf("1\n");
	}
    }

    return 0;
}


你可能感兴趣的:(POJ 2406 Power Strings)