题意简述
给出两个字符串s1和s2,其中s2为s1的子串,求出s2在s1中所有出现的位置。
代码
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int nxt[1000010];
char st1[1000010], st2[1000010];
void cnxt(char* st, int l)
{
int x = -1;
nxt[0] = -1;
for (register int i = 1; i < l; ++i)
{
while (x > -1 && st[i] != st[x + 1]) x = nxt[x];
if (st[i] == st[x + 1]) ++x;
nxt[i] = x;
}
}
void kmp(char* st1, int l1, char* st2, int l2)
{
int x = -1;
cnxt(st2, l2);
for (register int i = 0; i < l1; ++i)
{
while (x > -1 && st1[i]!=st2[x + 1]) x = nxt[x];
if (st1[i] == st2[x + 1]) ++x;
if (x == l2 - 1) printf("%d
", i - l2 + 2);
}
}
int main()
{
ios::sync_with_stdio(false);
cin >> st1 >> st2;
kmp(st1, strlen(st1), st2, strlen(st2));
}