2015-8-19
原题简述:
一个带有 n 个字符的字符串 s ,要求找出 s 的前缀中具有循环结构的字符子串,也就是要输出具有循环结构的前缀的最后一个数下标与其对应最大循环次数。
原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1358
解题思路:
学过KMP算法的都知道其核心为next数组,因为next记录的是原字符串当前前缀的后缀的最大匹配长度,反过来就是当前前缀的前缀匹配长度(即可能存在的循环节长度)。
故利用好next数组能很快的解决这道题。
源代码:
/*
OJ: HDOJ
ID: forever
TASK: 1358.Period
LANG: C++
NOTE: KMP(next数组)
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 1000005
char str[MAX];
int n, next[MAX];
void getnext() {
next[0] = -1, next[1] = 0;
int i = 1, j = 0;
while( i < n ) {
if( j == -1 || str[i] == str[j] ) {
i ++, j ++;
next[i] = j;
}
else
j = next[j];
}
}
int main()
{
int cas = 1;
while( scanf( "%d", &n ), n ) {
std::cin >> str;
getnext();
printf( "Test case #%d\n", cas ++ );
for( int i = 2; i <= n; i ++ ) {
if( next[i] ) {
int tmp = i - next[i];
if( i % tmp == 0 )
printf( "%d %d\n", i, i / tmp );
}
}
printf( "\n" );
}
return 0;
}