C++KMP算法记录1

代码记录

参考:https://blog.csdn.net/v_july_v/article/details/7041827

   KMPTest.h

#pragma once
#include<iostream>
#include<string.h>
/*
	kmp 获取 next 数组方式
*/
void kmpGetNext(const char* matchStr, int* next, int len);

/*
	kmp算法实现
*/
int kmpAlogrithm(const char* str, const char* matchStr, int* next, int len);

KMPTest.cpp

#include"KMPTest.h"

using namespace std;

void kmpGetNext(const char* matchStr, int* next, int len) {
	int k = -1;
	next[0] = k;
	//next[1] = 0;
	//next[2] = 1;
	int j = 0;
	while (j < len-1)
	{
		if (k == -1 || matchStr[j] == matchStr[k]) {
			cout << "j = " << j << endl;
			k++;
			j++;
			if (matchStr[j] != matchStr[k]) {
				next[j] = k;
			}
			else {
				next[j] = next[k];
			}
			
		}
		else {
			k = next[k];
		}
	}

}

int kmpAlogrithm(const char* str, const char* matchStr, int* next, int len) {
	int str_len = strlen(str);
	int i = 0;
	int j = 0;
	int result = -1;
	while (i < str_len && j < len) //同时都小于各自的数据长度才可以
	{
		if (j == -1 || str[i] == matchStr[j]) {
			i++;
			j++;
		}
		else {
			j = next[j];
		}
		
	}
	if (j >= len) {
		result = i - j; 
	}
	return result;
}

测试运行上面的代码

int main(){
    const char* matchStr = "abababcd";
	const char* str = "aaccdabababcddsdfefsadf";
	int len = strlen(matchStr);
	int *next = (int*)malloc(sizeof(int)*len);
	if (!next) {
		cout << "next 开辟错误" << endl;
		return 0;
	}
	kmpGetNext(matchStr, next, len);
	cout << "next的值为:";
	for (int i = 0; i < len; i++)
	{
		cout << " " << next[i];
	}

	cout << endl;

	int result = kmpAlogrithm(str, matchStr, next, len);

	cout << "result = " << result << endl;

	if (next) {
		free(next);
		next = NULL;
	}
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值