数据结构与算法——KMP算法模板

KMP算法

KMP算法指的是字符串模式匹配算法,问题是:在主串T中找到第一次出现完整子串P时的起始位置。该算法是三位大牛:D.E.Knuth、J.H.Morris和V.R.Pratt同时发现的,以其名字首字母命名。
下面是KMP算法的C++版本:

#include <iostream>
#include <string>
#include <vector>

using namespace std;
//getNext
vector<int> getNext(string str2) 
{

   if (str2.length() == 1) {
   	vector<int> next{ -1 };
   	return next;
   }
   vector<int> next(str2.length());
   next[0] = -1;	next[1] = 0;
   int i = 2;	//当前来到的位置
   int cn = 0;	//比对的位置,要与i-1位置相比
   while (i < str2.length()) 
   {
   	if (str2[i - 1] == str2[cn]) //配上了
   		next[i++] = ++cn;
   	else if (cn > 0) //没配上,cn还可以往前跳
   		cn = next[cn];
   	else      //没配上,cn已经跳到了0位置
   		next[i++] = 0;
   }
   return next;
}
int KMP(string str1, string str2) 
{
   if (str2.length() < 1 || str1.length() < str2.length()) 
   	return -1;
   int i1 = 0;//str1比对位置
   int i2 = 0;//str2比对位置
   vector<int> next = getNext(str2);
   while (i1 <str1.length()  && i2 < str2.length()) 
   {
   	if (str1[i1] == str2[i2]) //相等共同往下动
   	{
   		i1++;
   		i2++;
   	}
   	else if (next[i2] == -1) //i2跳到了str2[0]
   		i1++;
   	else       //如果不匹配,i2跳到下一寻找位置
   		i2 = next[i2];
   }
   //返回起始位置
   return i2 == str2.length() ? i1 - i2 : -1;
}

int main()
{
   string str1 = "ABCCABCCABCCABCCDEFGH";
   string str2 = "CCDE";
   cout << KMP(str1, str2) << endl;	
   system("pause");
   return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值