题目来源于AcWing
题目如下:
给定一个字符串 S,以及一个模式串 P,所有字符串中只包含大小写英文字母以及阿拉伯数字。
模式串 P在字符串 S中多次作为子串出现。
求出模式串 P在字符串 S 中所有出现的位置的起始下标。
输入格式
第一行输入整数 N,表示字符串 P 的长度。
第二行输入字符串 P。
第三行输入整数 M,表示字符串 S 的长度。
第四行输入字符串 S。
输出格式
共一行,输出所有出现位置的起始下标(下标从 00 开始计数),整数之间用空格隔开。
数据范围
1≤N≤1051≤1e5
1≤M≤106≤1e6
输入样例:
3
aba
5
ababa
输出样例:
0 2
KPM算法是为了减少朴素算法中的匹配次数,其中最重要的就是如何创建next数组
这里先上代码:
vector<int> getNext(string& pattern) {
int m = pattern.size(); //模式串的长度
vector<int> next(m, 0); //初始化next数组
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && pattern[i] != pattern[j]) {
j = next[j - 1];
}
if (pattern[i] == pattern[j]) {
j++;
}
next[i] = j;
}
return next;
}
这里的pattern表示模式串,text表示文本串,这里不好解释,但是有笔算的方法可以帮你快速确定next数组,如下(字有点丑):
拿“ABCDABDCA”举例子:
-
初始时,令
i = 0
,j = -1
,next[0] = -1
。 -
对于每个
i >= 1
,不断执行以下步骤直到j
满足以下任意一个条件:-
j = -1
。 -
pattern[i - 1] = pattern[j]
。 -
此时令
j = next[j]
,回到步骤2。
-
-
根据上述步骤,可以得到以下
next
数组:pattern: A B C D A B D C A index: 0 1 2 3 4 5 6 7 8 next: -1 0 0 0 0 1 2 0 1
例如,next[6] = 2
表示当模式串中第6个字符(即字母'B')不匹配时,应该将模式串中第4个字符(即字母'D')与文本串中当前位置的字符进行比较。
之后就是KMP算法,代码如下:
int kmp(string& text, string& pattern) {
int n = text.size(), m = pattern.size();
vector<int> next = getNext(pattern);
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && text[i] != pattern[j]) {
j = next[j - 1];
}
if (text[i] == pattern[j]) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
完整代码模板如下:
#include <iostream>
#include <vector>
using namespace std;
// 构造next数组
vector<int> getNext(string& pattern) {
int m = pattern.size();
vector<int> next(m, 0);
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && pattern[i] != pattern[j]) {
j = next[j - 1];
}
if (pattern[i] == pattern[j]) {
j++;
}
next[i] = j;
}
for (auto& i : next) {
cout << i << " ";
}
return next;
}
// KMP算法
int kmp(string& text, string& pattern) {
int n = text.size(), m = pattern.size();
vector<int> next = getNext(pattern);
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && text[i] != pattern[j]) {
j = next[j - 1];
}
if (text[i] == pattern[j]) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
int main() {
string text = "ABABABCABAABABABCDABDABA";
string pattern = "ABCDABDCA";
int pos = kmp(text, pattern);
puts("");
if (pos == -1) {
cout << "未找到匹配的模式串" << endl;
} else {
cout << "模式串在文本串中的起始位置为:" << pos << endl;
}
return 0;
}
当然,这道题目的代码如下:
#include <iostream>
using namespace std;
const int N = 1e5 + 10, M = 1e6 + 10;
int ne[N];
char s[M], p[N];
int main()
{
int m,n;
cin >> n >> p + 1 >> m >> s + 1;
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;
}
for (int i = 1, j = 0; i <= m; i ++ )
{
while (j && s[i] != p[j + 1]) {
j = ne[j];
}
if (s[i] == p[j + 1]) {
j ++;
}
if (j == n)
{
printf("%d ", i - n);
j = ne[j];
}
}
return 0;
}
若有错,请纠正,谢谢