#include<iostream>
using namespace std;
int strlen(char* S)
{
int i = 0;
int counter = 0;
while (S[i] != '\0') {
i++;
counter++;
}
return counter;
}
void get_next(char* T, int *next)
{
int i =0,j = -1;
next[0] = -1;
while (T[i]!='\0') {
if (j==-1 || T[i] == T[j]) {
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
int index_KMP(char* S, char* T, int pos)
{
int i = pos-1;
int j = 0;
int next[255];
get_next(T, next);
while (i<strlen(S) && j<strlen(T)) {//注意这里千万不能写成T[i]!='\0' && S[j]!='\0'
if (j == -1 || S[i] == T[j]) {
i++;
j++;
}
else
j = next[j];
}
cout << "i= " << i << endl;
cout << "j= " << j << endl;
if (T[j] == '\0')
return i - j + 1;
else
return 0;
}
void get_nextval(char* T, int *nextval)
{
int i = 0, j = -1;
nextval[0] = -1;
while (T[i] != '\0') {
if (j == -1 || T[i] == T[j])
{
i++;
j++;
if (T[i] != T[j])
nextval[i] = j;
else
nextval[i] = nextval[j];
}
else
j = nextval[j];
}
}
int main()
{
int next[255];
char* S = "aaabbbaaabbb";
char* T = "bbb";
cout << index_KMP(S, T, 5)<< endl;
system("pause");
return 0;
}
KMP模式匹配
最新推荐文章于 2024-06-22 16:18:48 发布