KMP实现

本文介绍了一种高效的字符串匹配算法——KMP算法,并通过C++代码详细展示了两种不同的KMP算法实现方式,包括next数组和nextval数组的计算过程。通过对主串和模式串的比较,能够快速定位模式串在主串中的起始位置。
#include<iostream>
#include<string>
#include<stack>
using namespace std;

class Solution{
public:
	void getNext(int* next, const string& s)
	{
		int j = 0;
		next[0] = 0;
		for (int i = 1; i < s.size(); i++)
		{
			while (s[i] != s[j] && j > 0) {
				j = next[j - 1];
			}
			if (s[i] == s[j]) {
				j++;
			}
			next[i] = j;
		}
	}

	//统一减一
	void getnext(int* next, const string& s) {
		int j = -1;
		next[0] = j;
		for (int i = 1; i < s.size(); i++) {
			while (s[i] != s[j+1] && j > -1) {
				j = next[j];
			}
			if (s[i] == s[j+1])
			{
				j++;
			}
			next[i] = j;
		}
	}

	int strStr(string haystack, string needle) {
		if (needle.size() == 0) return 0;
		int size = needle.size();
		int* p =new int[size];
		//int next[needle.size()];
		getNext(p, needle);
		int j = 0;
		for (int i = 0; i < haystack.size(); i++) {
			while (j > 0 && haystack[i] != needle[j]) {
				j = p[j-1];
			}
			if (haystack[i] == needle[j])
			{
				j++;
			}
			if (j == needle.size()) {
				return (i - needle.size() + 1);
			}
		}
		return -1;
	}

	int strStr1(string haystack, string needle) {
		if (needle.size() == 0) return 0;
		int size = needle.size();
		int* p = new int[size];
		//int next[needle.size()];
		getnext(p, needle);
		int j = -1;
		for (int i = 0; i < haystack.size(); i++) {
			while (j >= 0 && haystack[i] != needle[j+1]) {
				j = p[j];
			}
			if (haystack[i] == needle[j+1])
			{
				j++;
			}
			if (j == needle.size()-1) {
				return (i - needle.size() + 1);
			}
		}
		return -1;
	}

};



void main() 
{
	string hay, need;
	hay = "helloeeessaabaabaafdas";
	need = "aabaaf" ;
	Solution s;
	cout<<s.strStr(hay,need)<<endl;
	cout << s.strStr1(hay, need) << endl;
	system("pause");

}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值