7-1 【模板】KMP字符串匹配 (20 分)
给出两个字符串text和pattern,其中pattern为text的子串,求出pattern在text中所有出现的位置。
为了减少骗分的情况,接下来还要输出子串的前缀数组next。
输入格式:
第一行为一个字符串,即为text。
第二行为一个字符串,即为pattern。
输出格式:
若干行,每行包含一个整数,表示pattern在text中出现的位置。
接下来1行,包括length(pattern)个整数,表示前缀数组next[i]的值,数据间以一个空格分隔,行尾无多余空格。
输入样例:
ABABABC
ABA
输出样例:
1
3
0 0 1
#includeusing namespace std; int next2[100005]; int len_s = 0; int len_t = 0; void get_next(string t, int next1[]) { int i = 0, j = -1; next1[0] = -1; while(t[i] != ' ') { if(j == -1 || t[i] == t[j]) { ++i, ++j; next1[i] = j; } else j = next1[j]; } } void Index_KMP(string s, string t) { int i = 0, j = 0; while(i < len_s) { if(j == -1 || s[i] == t[j]) ++i, ++j; else j = next2[j]; if(j == len_t) { cout << i - len_t + 1 << endl; j = next2[j]; } } } int main() { string s, t; cin >> s; cin >> t; int i = 0; while(s[i] != ' ') i++; len_s = i; i = 0; while(t[i] != ' ') i++; len_t = i; get_next(t, next2); Index_KMP(s, t); cout << next2[1]; for(int i = 2; i <= len_t; i++) cout << " " << next2[i]; return 0; }



