[Ybtoj High-efficiency Advanced 2.3] [kmp] Substring search

[Ybtoj High-efficiency Advanced 2.3] [kmp] Substring search

topic

Insert picture description here


Problem-solving ideas


The strategy of kmp template question kmp is to adjust kkk point position (decreasekkk value) and makekkThe value of k is as large as possible so thatAAA[ i i i- j j j+1… i i i]= B B B[1… j j j ] Keep matching and try to matchAAA[ i i i +1] GiveBBB[ j j j+1]

board

for (int i=1;i<=len1;i++)
	{
    
    
		while (k!=0&&x[i]!=y[k+1]) k=next[k];
		if (x[i]==y[k+1]) k++;
		if (k==len2) ans++;  
	}

Explanation of the manual push process
P. S PSP.S n e x t next n e x t isBBThe string B matches itself
is xx in the boardxyyy ran out the same
Insert picture description here


Code

#include<iostream> 
#include<cstring>
#include<cstdio>
using namespace std;
int len1,len2,ans;
int next[1000010]; 
char x[1000010],y[1000010];
int main()
{
    
    
	scanf("%s%s",x+1,y+1);
	len1=strlen(x+1); 
	len2=strlen(y+1);
	next[1]=0;
	int k=0;
	for (int i=2;i<=len2;i++)
	{
    
     
		while (k>0&&y[i]!=y[k+1]) k=next[k];
		if (y[i]==y[k+1]) k++;
		next[i]=k; 
	}  //B串自己匹配,求出next
	k=0;
	for (int i=1;i<=len1;i++)
	{
    
    
		while (k!=0&&x[i]!=y[k+1]) k=next[k];
		if (x[i]==y[k+1]) k++;
		if (k==len2) ans++;  //完全匹配,次数+1
	}  //A串和B串匹配
	printf("%d\n",ans);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_45621109/article/details/115021236