Kmp字符匹配算法优化C++实现

C++实现Kmp字符匹配算法的优化版

 

头文件:KmpAlgorithm.h

#ifndef KMPALGORITHM_H
#define KMPALGORITHM_H
#include <string>
#include <iostream>
class KmpAlgorithm{
	std::string s; //主串
	std::string t; //子串
	static const int MaxSize = 255;
	int next[MaxSize];
	void Get_Next(); //T串的模式匹配函数
public:
	KmpAlgorithm(){
		std::memset(next,0,sizeof(int) * 255);
		printf("请输入要匹配的字符串的主串:\n");
		std::cin >> s;
		printf("请输入要匹配的字符串的子串:\n");
		std::cin >> t;
	}
	int Index_Kmp(int pos);  //字符匹配函数
};
#endif //KMPALGORITHM_H


实现文件:KmpAlgorithm.cpp

#include "KmpAlgorithm.h"
void KmpAlgorithm::Get_Next()
{
	int i,j;
	i = 0;
	j = -1;
	next[0] = -1;
	while(i < t.size()-1)
	{
		if(j == -1 || t[j] == t[i]) //如果相等则继续
		{							//next[0] == -1 j的值有可能回溯为-1数组越界
			++i;
			++j;
			if(t[j] != t[i]) //如果下面两个字符不相等则把j的值赋给next在i位置的值
				next[i] = j;
			else
				next[i] = next[j]; //相等则把next在j位置的值赋给next在i位置的值
		}
		else
			j = next[j];
	}
}
int KmpAlgorithm::Index_Kmp(int pos) //字符匹配函数
{
	int  i = pos - 1; //数组从下标0开始
	int j = 0;
	Get_Next(); 
	while(i < s.size() && j < t.size()) 
	{
		if(j == -1 || s[i] == t[j]) //如果相等继续
		{							//如果j的值回溯到-1 next[0] == -1 则继续否则数组越界
			++i;
			++j;
		}
		else
		{
			j = next[j]; //不相等则回溯
		}
	}
	if(j >= t.size()) //匹配成功返回在主串中的位置
		return i - t.size() + 1;
	else
		return -1; //失败返回-1
}
	


测试文件:main.cpp

#include "KmpAlgorithm.h"
#include <iostream>
using namespace std;
int main()
{
	int pos = 0;
	KmpAlgorithm km;
	printf("请输入在主串的第几个字符开始匹配:\n");
	scanf("%d",&pos);
	int position = km.Index_Kmp(pos);
	if(position == -1)
		printf("在主串中未找到与子串匹配的字符:\n");
	else
		printf("在主串的第%d个位置匹配成功\n",position);
	return 0;
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值