kmp

// idx代表已经匹配到的位置
void get_next(string &p) {
	to = vector<int>(n, -1);
	to.clear();
	int idx = -1;
	for (int i = 1; i < n; ++i) {
		while(idx != -1 && p[idx + 1] != p[i]) 
			idx = to[idx];
		to[i] = p[idx + 1] == p[i] ? ++idx : -1;
	}
}

// 这里是返回从p的开头匹配到s的结尾的字符串
// idx代表已经匹配到的位置
string kmp(string& s, string& p) {
	int idx = -1;
	for (int i = 0; i < n; ++i) {
		while(idx != -1 && s[i] != p[idx + 1])
			idx = to[idx];
		if (s[i] == p[idx + 1]) idx++;
	}
	return s + p.substr(idx + 1);
}

posted @ 2024-07-19 09:42  FlyingLight  阅读(3)  评论(0编辑  收藏  举报