kmp字符串匹配算法

//头文件
#ifndef KMP_H
#define KMP_H
#include
   
   
    
    
#include
    
    
     
     
using namespace std;
class kmp{
private:
	string value, pString;
	int *pStr;//特征向量
public:
	void setValue();
	string getValue();
	void getpStr();
	bool KMPMatch();
	void simulate();
};
void kmp::setValue()
{
	cout << "input the value:    ";
	cin >> value;
	cout << "input the pString:   ";
	cin >> pString;
}
string kmp::getValue()
{
	return pString;
}
void kmp::getpStr()
{
	//开辟特征向量空间的大小,并将第一个字符的特征向量定为0
	int count = this->pString.length();
	pStr = new int[count];
	pStr[0] = 0;
	int k = 0;
	for (int i = 1; i < count; i++)
	{
		//在匹配字符串的预处理时期,最终要的是要看前一个字符的特征向量出的值
		//然后将要比较的字符和pStr[k]处的字符相比较,如果相同则该位置的特征向量等于前一位置的特征向量加一
		//如果前一位置的特征向量=0,但是当前位置的字符与pStr[k]即pStr[0]的字符相等,当前位置的特征向量=k+1
		//如果k=0,且当前位置与pStr[k]即pStr[0]的字符不相等,则此处的特征向量值等于0
		k = pStr[i - 1];
		while (k>0 && this->pString[i] != this->pString[k])
			k = pStr[k - 1];
		if (this->pString[i] == this->pString[k])
			pStr[i] = k + 1;
		else
			pStr[i] = 0;
	}
}
bool kmp::KMPMatch()
{
	int count = this->value.length();
	int number = this->pString.length();
	if (number > count)
		return false;
	int i = 0, j = 0;
	while (i < count&&j < number)
	{
		if (this->value[i++] == this->pString[j])
		{
			//i++必须写在this->value[i++]中,否则会出现字符串长度长是的死循环现象
			j++;
		}
		else
		{
			//此时,出现字符不相等的情况,开始查看该位置处的特征向量,然后将要查找的字符串的位置移到
			//特征向量所指向的位置,而模式字符串则不发生变化即j的值不发生变化
			j = pStr[j];
		}
	}
	//如果j>=number则说明匹配成功
	if (j >= number)
		return true;
	return false;
}
void kmp::simulate()
{
	bool flag = true;
	while (flag)
	{
		this->setValue();
		this->getpStr();
		flag = this->KMPMatch();
		if (flag)
		{
			cout << "succeed" << endl;
		}
		else
			cout << "failer" << endl;
	}
}
#endif
//主函数
#include"kmp.h"
int main(int argc, char argv[])
{
	kmp user;
	user.simulate();
	return 0;
}
    
    
   
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值