#ifndef KMP_H_
#define KMP_H_
#include<iostream>
/**
* 寻找子串在主串中第一次出现的位置
* 朴素模式匹配算法
*/
int GetIndex1(char* S, char* T)
{
int Slen = strlen(S);
int Tlen = strlen(T);
std::cout << Slen << "\t" << Tlen << std::endl;
int i = 0, j = 0;
while(i<Slen && j<Tlen)
{
if (S[i] == T[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == Tlen )
return i - j;
else
return -1;
}
/**
* 获取KMP算法中的next数组
*/
void GetArrayNext(char* S,int *next)
{
/**
*https://www.cnblogs.com/dusf/p/kmp.html
*/
int j, k;
j = 0;
k = -1;
next[0] = -1;
while (j < strlen(S) - 1)
{
if (k == -1 || S[k] == S[j])
{
j++;
k++;
//如果移动之后还相等,则跳过
if (S[j] == S[k])
{
next[j] = next[k];
}
else
{
next[j] = k;
}
}
else
{
k = next[k];
}
}
}
/**
* KMP算法
*/
int GetIndex_KMP(char* S, char* T)
{
int Slen = strlen(S);
int Tlen = strlen(T);
int* next = new int[Tlen];
GetArrayNext(T, next);
int i, j;
i = j = 0;
while (i < Slen && j < Tlen)
{
if (j == -1 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
delete[] next;
if (j >= Tlen)
{
return i - Tlen;
}
else
return -1;
}
#endif // !KMP_H_
KMP算法
最新推荐文章于 2024-07-11 22:03:57 发布