【Ybtoj 第8章例题2】重复子串【KMP】

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


解题思路

处理出数组 p p p,设字符串长度为 n n n,则模式串第 1 1 1位到第 p [ n ] p[n] p[n]位与模式串第 n − p [ n ] n-p[n] np[n]位到第n位是匹配的。所以如果 n m o d ( n − p [ n ] ) = = 0 n mod (n-p[n])==0 nmodnp[n]==0,则存在重复连续子串,长度为 n − p [ n ] n-p[n] np[n],循环次数为 n / n − p [ n ] n/n-p[n] n/np[n]


代码

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

char s[1000010];
int l,i,j,p[1000010]; 

int main(){
    
    
	scanf("%s",s+1);
	l=strlen(s+1); 
	while(s[1]!='.'||l!=1){
    
    
		i=1;j=0;
		for(int i=1;i<l;i++)
		{
    
    
			while(j>0&&s[i+1]!=s[j+1])
				j=p[j];
			if(s[i+1]==s[j+1])
				j++;
			p[i+1]=j;
		}
		if(l%(l-p[l])==0)
			printf("%d\n",l/(l-p[l]));
		else printf("1\n");
		scanf("%s",s+1);
		l=strlen(s+1); 
		memset(p,0,sizeof(p));
	}
}

猜你喜欢

转载自blog.csdn.net/kejin2019/article/details/114440886
今日推荐