最长公共前缀 CSU

#include <iostream>
#include <cstring>
using namespace std;
const int N = 10010, M = 100010;
int n, m;
int ne[N];//ne[i] : 以i为结尾的部分匹配的值
char s[N], p[N];
int main() {
	int t;
	cin>>t;
	while(t--) {
		int ans=0;
		cin>>s+1>>p+1; 
		n=strlen(p+1);
		m=strlen(s+1);
		//求next过程
		//i从2开始,因为next[1]=0
		//如果第一个字母失败了,只能从0开始
		for (int i = 2, j = 0; i <= n; i ++ ) {
			while (j && p[i] != p[j + 1])    j = ne[j];
			if (p[i] == p[j + 1])    j ++ ;
			ne[i] = j;
		}
		//kmp匹配过程
		for (int i = 1, j = 0; i <= m; i ++ ) {
			while (j && s[i] != p[j + 1])    //当j没有退回起点,并且当前的s[i]不能和下一个j的位置匹配
				j = ne[j];//移动,保证之前的相等  直到匹配位置,或者j已经到开头了
			if (s[i] == p[j + 1]) //如果已经匹配了
				j ++ ;  //j往下移动
			if (j == n) {//说明匹配成果
				ans++;
				j = ne[j];
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/QingyuYYYYY/p/12383553.html