[KMP算法]A. 【例题1】子串查找


题目解析

这道题是比较基础的KMP模板, KMP是一种高效的字符串匹配算法。

以下这个视频是我认为是讲的不错的KMP算法视频
视频连接

Code

#include <bits/stdc++.h> 
using namespace std;

char s1[1000005], s2[1000005];
int len1, len2, j, kmp[1000005], ans;

int main ()
{
	cin >> s1 + 1; len1 = strlen (s1 + 1);
	cin >> s2 + 1; len2 = strlen (s2 + 1);
	for (int i = 2; i <= len2; ++ i)
	{
		while (j && s2[i] != s2[j + 1]) j = kmp[j];
		if (s2[i] == s2[j + 1]) ++ j;
		kmp[i] = j;
	}
	j -= j;
	for (int i = 1; i <= len1; ++ i)
	{
		while (j && s1[i] != s2[j + 1]) j = kmp[j];
		if (s1[i] == s2[j +1]) ++ j;
		if (len2 == j)
		{
			ans ++;
			j = kmp[j];
		}
	}
	printf ("%d", ans);
	return 0;
}
posted @ 2021-05-20 15:47  unknown_future  阅读(107)  评论(0编辑  收藏  举报