问题描述:
给定文本串
s
s
s 与模式串
t
t
t,使用KMP算法求
s
s
s 中有多少个子串与
t
t
t 相同,两个子串视为不同仅当他们长度不等或起始位置不同。
思路:
KMP算法在网上有很多详细的讲解了,主要是利用匹配失败时的残留信息来减少匹配的次数,这边不做赘述。
源代码:
//
// main.cpp
// KMP
//
// Created by 胡昱 on 2021/12/3.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
// 共T组测试数据
int T;
cin >> T;
while((T--) > 0) {
// 输入文本串和模式串
int textL, patternL;
cin >> textL >> patternL;
char* text = new char[textL];
char* pattern = new char[patternL];
for(int i = 0; i < textL; ++i) {
cin >> text[i];
}
for(int i = 0; i < patternL; ++i) {
cin >> pattern[i];
}
// 初始化结果
int result = 0;
// 如果模式串长度为1,则直接匹配就够了
if(patternL == 1) {
for(int i = 0; i < textL; ++i) {
if(text[i] == pattern[0]) {
++result;
}
}
cout << result << endl;
continue;
}
// 计算模式串pattern的next数组
// next[i] 表示 P[0] ~ P[i] 这一个子串,使得前k个字符恰等于后k个字符的最大的k
// 特别地,k 不能取 i + 1(因为这个子串一共才 i + 1 个字符,自己肯定与自己相等,就没有意义了)
int* next = new int[patternL];
next[0] = 0; // next[0]必然是0
int ni = 1, now = 0;
while(ni < patternL) {
if(pattern[now] == pattern[ni]) {
++now;
next[ni] = now;
++ni;
}
else if(now != 0) {
now = next[now - 1];
}
else {
next[ni] = 0;
++ni;
}
}
// 开始使用next进行KMP算法
int ti = 0, pi = 0;
while(ti < textL) {
// 若匹配到相同字符,则两个串都向前走
if(text[ti] == pattern[pi]) {
++ti;
++pi;
}
// 如果匹配失败,且模式串下标pi不在首位,则使用next数组决定模式串下标pi的新值
else if(pi != 0) {
pi = next[pi - 1];
}
// 如果匹配失败,且模式串下标pi在首位,则直接移动主串下标即可
else {
++ti;
}
// 判断是否匹配成功
if(pi == patternL) {
++result;
pi = next[pi - 1];
}
}
// 输出结果并释放资源
cout << result << endl;
delete [] text;
delete [] pattern;
delete [] next;
}
return 0;
}