KMP算法模板
Description
\(txt\)为文本串,\(pat\)为模式串。
\(nxt[i]\):\(pat[0:i-1]\)中后缀等于前缀的最大长度。
Input
第一行给出文本串\(txt\),第二行给出模式串\(pat\)。
Output
如果匹配到,输出"Found!",否则输出"Not Found!"。
Sample Input
abaabaab
aaba
Sample Output
Found!
Code
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 1e3 + 10;
int nxt[N];
bool kmp(char txt[], char pat[])
{
int ltxt = strlen(txt);
int lpat = strlen(pat);
for (int i = 0, j = -1; i <= lpat; i++, j++)
{
nxt[i] = j;
while (~j && pat[i] != pat[j]) j = nxt[j];
}
for (int i = 0, j = 0; i <= ltxt; i++, j++)
{
if (j == lpat) return true;
while (~j && txt[i] != pat[j]) j = nxt[j];
}
return false;
}
char txt[N], pat[N];
int main()
{
scanf("%s%s", txt, pat);
bool f = kmp(txt, pat);
printf("%s\n", f ? "Found!" : "Not Found!");
return 0;
}