在文本串中寻找模式串的位置
kmp算法本质通过next数组来寻找字符串
next数组表示i位之前的字符串最大相同前缀后缀的长度
每次匹配失配时,只需要跳转到该位的next[i],因为模式串next[i]位置前面的字符串一定和现在文本串相同,通过此过程就可寻找到该模式串
#include<iostream>
using namespace std;
int nx[10000+5];
char b[100000+5], a[1000000+5]; //b为模式串 a为文本串
int n, m;
void getnext(){
int k = -1, j = 0;
nx[0] = -1;
while(j < m){
if(k == -1 || b[j] == b[k]) nx[++j] = ++k;//j位置之前 最大前缀后缀相同的长度
else k = nx[k];
}
}
int KMP()
{
int flag = -1;
for(int i = 0, j = 0; i < n; i++){
while(j > 0 && b[j] != a[i]) j = nx[j];
if(a[i] == b[j]) j++;
if(j == m)
{
return i - j + 2;
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while(t--){
cin >> n >> m;
for(int i = 0; i < n; i++) cin >> a[i];
for(int i = 0; i < m; i++) cin >> b[i];
getnext();
cout << KMP() << endl;
}
return 0;
}