KMP算法

转载https://blog.csdn.net/LEE18254290736/article/details/77278769

https://blog.csdn.net/yearn520/article/details/6729426这里的next讲解特别详细清楚

#include<iostream>
#include<vector>
#include<string>
using namespace std;
//求next数组
void solve_next(char *a, int n, int *next){
	next[0] = 0;//初始化
	for (int i = 1; i < n; i++){
		int k = next[i - 1];
		while (a[i] != a[k] && k != 0){//寻找子对称
			k = next[k - 1];
		}
		if (a[i] == a[k])
		{
			//找到了子对称
			next[i] = k + 1;
		}
		else{
			//找不到
			next[i] = 0;
		}

	}
}
int kmp_search(char *src,int s_len,char* pat,int p_len,int *next){
	int i = 0, j = 0;
	while (i < s_len&&j < p_len){
		if (j==-1||src[i] == pat[j]){
			i++; j++;
		}
		else{
			j = next[j]-1;
		}
	}
	if (j >= p_len)return i - p_len + 1;//返回的是匹配的第i位
	else return -1;
}
int main(){
	char a[16] = { 'a', 'g', 'c', 't', 'a', 'g', 'c', 'a', 'g', 'c', 't', 'a', 'g', 'c', 't','g' };
	int next[16];
	solve_next(a, 16, next);
	for (int i = 0; i < 16; i++)
		cout << next[i] << " ";
	cout << endl;
	char pat[5] = { 'a', 'b', 'a', 'b', 'c' };
	char src[13] = { 'a', 'b', 'a', 'b','e', 'e', 'b', 'a', 'b', 'c', 'b', 'c', 'c' };
	int next1[5];
	solve_next(pat, 5, next1);
	for (int i = 0; i < 5; i++)
		cout << next1[i] << " ";
	cout << endl;
	cout << kmp_search(src, 13, pat, 5, next1);
	cout << endl;
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值