字符串匹配(find函数,KMP算法,Sunday算法)

刚刚手贱把文章点了舍弃……心都碎了……

首先是find函数:

可以返回找到的字符串在String里的位置,while里的条件写得比较精炼

string temp; cout << "输入匹配的:"; cin >> temp;
string pipei; cout << "输入被匹配的: "; cin >> pipei;
int position = 0;
int temp_result = 0;
//pipei.find_first_of()
while ((position = pipei.find(temp, position)) != string::npos)
{			temp_result++;
//position=s.find_first_of(flag,position);
cout << "第" << temp_result << "个位置: " << position << endl;
position++;

}

KMP算法,直接把看到的写得比较好的粘贴上来了

见右:http://blog.csdn.net/yutianzuijin/article/details/11954939/

Sunday算法:

原理看的百度百科的,顺手实现了下,比KMP可人多了……

#include<unordered_map>
#include<iostream>
#include<string>
#include<vector>
using namespace std;


int main() {
	int a;
	cin >> a;//比较的组数
	vector<int>result(a);


	for (int ii = 0; ii < a; ++ii) {

		string temp;  cin >> temp;//短的那个
		string pipei; cin >> pipei;
		int n = temp.size(), m = pipei.size();
		int temp_result = 0;

		//对temp处理
		unordered_map<char, int>mapping;
		for (int iii = 0; iii < n; ++iii) { mapping[temp[iii]] = iii + 1; }//+1的作用是把0撇开
        
		for (int i = 0; i < m-n+1;) {
			if (temp == pipei.substr(i, n)) { temp_result++; }
			if (i + n < m) { 
				if (mapping[pipei[i + n]] == 0)
					i += (n+1); 
			    else i += (n - mapping[pipei[i + n]] + 1); 
			}
			else i++;
		}


		result[ii] = temp_result;

	}
	for (int i = 0; i < result.size(); ++i)cout << result[i] << endl;
	system("pause");
}

刷题刷得略惆怅…

《字符串匹配(find函数,KMP算法,Sunday算法)》

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