算法模板之KMP(HDU 2087 剪花布条)

模板总结归纳:

vector <int> kmp(string pattern, string text){
	int n = pattern.size();
	vector <int> next(n + 1, 0);
	for(int i = 1; i < n; i++){
		int j = 1;
		while(j > 0){
			j = next[j];
			if(pattern[j] == pattern[i]){
				next[i + 1] = j + 1;
				break;
			}
		}
	}
	vector <int> positions;
	int m = text.size();
	for(int i = 0, j = 0; i < m; i++){
		if(j < n && text[i] == pattern[j]){
			j++;
		}else{
			while(j > 0){
				j = next[j];
				if(text[i] == pattern[j]){
					j++;
					break;
				}
			}
		}
		if(j == n){
			positions.push_back(i - n + 1);
		}
	}
	return positions;
}

实战模板题 :HDU 2087 剪花布条

//HDU 2087 剪花布条
#include<iostream>
#include<cstdio>
#include<string>
#include<vector> 

using namespace std;

vector <int> kmp(string pattern, string text){
	int n = pattern.size();
	vector <int> next(n + 1, 0);
	for(int i = 1; i < n; i++){
		int j = 1;
		while(j > 0){
			j = next[j];
			if(pattern[j] == pattern[i]){
				next[i + 1] = j + 1;
				break;
			}
		}
	}
	vector <int> positions;
	int m = text.size();
	for(int i = 0, j = 0; i < m; i++){
		if(j < n && text[i] == pattern[j]){
			j++;
		}else{
			while(j > 0){
				j = next[j];
				if(text[i] == pattern[j]){
					j++;
					break;
				}
			}
		}
		if(j == n){
			positions.push_back(i - n + 1);
		}
	}
	return positions;
}

int main()
{
	string a, b;
	while(cin >> a && a != "#"){
		cin >> b;
		vector <int> ans = kmp(b, a);
		int temp = -1, tot = 0;
		for(int i = 0; i < ans.size(); i++)
		{
			if(ans[i] - temp < b.size() && temp != -1){
				continue;
			}
			else{
				tot++;
				temp = ans[i];
			}
		}
		cout << tot << endl;
	}	
	return 0;
} 

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/lonelydoge/article/details/80112019
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞