#12 14TLE 求调
查看原帖
#12 14TLE 求调
1449395
wjc_23330126楼主2025/1/5 14:20
#include<iostream>
using namespace std;
#include<string>

void BuildMatch(string pattern,int* match,int n){
	match[0] = -1;
	for (int j = 1; j < n; j++) {
		int i = match[j - 1];
		while (i >= 0 && pattern[i+1] != pattern[j]) {
			i = match[i];
		}
		if (pattern[i+1] == pattern[j]) {
			match[j] = i + 1;
		}
		else {
			match[j] = -1;
		}
	}
}

void KMP(string str, string pattern) {
	int s = str.size();
	int p = pattern.size();
	if (s < p) {
		return;
	}
	int* match = new int[p];
	BuildMatch(pattern, match, p);
	int flag = 1;
	for (int i = 0, j = 0;flag ; i = i - j + 1,j = 0) {
		while (i < s && j < p) {
			if (str[i] == pattern[j]) {
				i++;
				j++;
			}
			else if (j > 0) {
				j = match[j - 1] + 1;
			}
			else {
				i++;
			}
		}
		if (j == p) {
			cout << i - j + 1 << endl;
		}
		else {
			flag = 0;
		}
	}
	for (int i = 0; i < p; i++) {
		cout << match[i] + 1 << " ";
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	string str;
	string pattern;
	cin >> str >> pattern;
	KMP(str, pattern);
}
2025/1/5 14:20
加载中...