0
点赞
收藏
分享

微信扫一扫

[C++] KMP算法

KMP算法

#include <iostream>
using namespace std;

void GetNext(const char* sub, int* next,int lensub)
{
next[0] = -1;
next[1] = 0;
int i = 2;
int k = 0;
while(i < lensub)
{
if (k ==-1 || sub[i - 1] == sub[k]) //k==-1 意思是 前后缀没对应 使得 next[i] = 0
{
next[i] = k + 1;
i++;
k++;
}
else
{
k = next[k]; //找下标
}
}

}

int KMP(const char* str, const char* sub, int pos)
{
int lenstr = strlen(str);
int lensub = strlen(sub);
if (lenstr == 0 || lensub == 0)
return -1;
if (pos < 0 || pos >= lenstr)
return -1;

int* next = (int *)malloc(sizeof(int)*lensub);
GetNext(sub,next,lensub);

int i = pos; //遍历主串
int j = 0; //遍历字串

while (i < lenstr && j < lensub)
{
if (j== -1||str[i] == sub[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j >= lensub)
return i-j;
return -1;
}

int main()
{
cout << KMP("abcabcabcsabc","ac",0)<<endl; //-1
cout << KMP("adbacd","ac",0)<<endl; //3
return 0;
}
举报

相关推荐

0 条评论