代码记录
参考: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;
}