跳转链接
https://www.acwing.com/problem/content/833/ 来源:模板题
题目描述
给定一个模式串 S,以及一个模板串 P,所有字符串中只包含大小写英文字母以及阿拉伯数字。 模板串 P 在模式串 S 中多次作为子串出现。 求出模板串 P 在模式串 S 中所有出现的位置的起始下标。
输入格式 第一行输入整数 N,表示字符串 P 的长度。 第二行输入字符串 P。 第三行输入整数 M,表示字符串 S 的长度。 第四行输入字符串 S。 输出格式 共一行,输出所有出现位置的起始下标(下标从 0 开始计数),整数之间用空格隔开。 数据范围 1 10^5^ 1 10^6^
输入样例1
3 aba 5 ababa 输出样例1 0 2
题解思路
参考https://www.acwing.com/solution/content/14666/
代码
cpp
//无注释版
#include <iostream>
using namespace std;
const int N = 1e5 + 10, M = 1e6 + 10;
int n, m;
int ne[N];
char p[N], s[M];
int main()
{
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)
{
cout << i - n << ' ';
j = ne[j];
}
}
return 0;
}cpp
//注释版
#include <iostream>
using namespace std;
const int N = 1e5 + 10, M = 1e6 + 10; // M为模式串长度,N匹配串长度
int n, m;
int ne[N]; // next[]数组,避免和头文件next冲突
char p[N], s[M]; // s为模式串, p为匹配串
int main()
{
cin >> n >> p + 1 >> m >> s + 1; // 下标从1开始
// 求next[]数组
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) // 满足匹配条件,打印开头下标, 从0开始
{
cout << i - n << ' ';
j = ne[j]; // 再次继续匹配
}
}
return 0;
}
