半条命16吧 关注:393贴子:26,041
  • 0回复贴,共1
#include "stdafx.h"
#include<iostream>
#include<string>
#include "cstdio"
using namespace std;
void get_next(string s, int next[]) {
int i = 1, j = 0;
next[1] = 0;
while (i < s.length()) {
if (j == 0 || s[i] == s[j]) {
i++; j++;
next[i] = j;
}
else
j = next[j];
}
}
void KMP(string s, string t, int next[]) {
int i = 1, j = 1;
while (i < s.length() && j < t.length()) {
if (j == 0 || s[i] == t[j]) {
i++; j++;
}
else j = next[j];
}
if (j >= t.length()) {
cout << i - t.length() << endl;
}
else {
cout << "NotFound" << endl;
}
}
int main() {
string String, Pattern;
int next[10000];
int m;
cin >> String;
String = " " + String;
scanf("%d", &m);
getchar();
for (int i = 0; i < m; i++) {
cin >> Pattern;
Pattern = " " + Pattern;
get_next(Pattern, next);
KMP(String, Pattern, next);
}
system("pause");
return 0;
}


IP属地:河南来自Android客户端1楼2021-04-12 19:44回复