跳到正文

个人记录

算法进阶指南——KMP求字符串最短循环节

褚觅山约 1 分钟
原文
文章信息与版本

文章信息

发布
2021年1月17日
收录
2026年1月30日
更新
2026年11月18日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

P74 ACWing141 这题实现起来比较简单,需要注意的是对KMP算法正确的理解。 书上的KMP算法和之前学过的有所区别,需要仔细体会。 相关的书上的证明也很nice,自己去看吧。

PS: 还需注意的一点是流输出较慢,对于有大量输出要求的采用printf函数输出。

代码如下:

C++
#include<iostream>
#include<string>
using namespace std;
void next(string a,int nex[]){
	int len=a.size();
	nex[1]=0;
	for(int i=2,j=0;i<=len;++i){
		while(j>0&&a[i-1]!=a[j])
			j=nex[j];
		if(a[i-1]==a[j])
			nex[i]=++j;
		else
			nex[i]=0;
	}
	return ;
}
int main(){
	int n;
	string a;
	scanf("%d",&n);
	int count=1;
	while(n!=0){
		int nex[n+3];
		cin>>a;
		printf("Test case #%d\n",count);
		count++;
		next(a,nex);
		for(int i=2;i<=n;++i){
			if(nex[i]>0&&i%(i-nex[i])==0)
				printf("%d %d\n",i,i/(i-nex[i]));
		}
		scanf("%d",&n);
		printf("\n");
	}
	return 0;
}
原文