KMP算法
gist: https://gist.github.com/genesislive/5081013
#include <iostream>
#include <cstring>
void get_nextval(const char *T, int nextval[])
{
int j = 0, k = -1;
nextval[0] = -1;
while (T[j] != '\0') {
if (k == -1 || T[j] == T[k]) {
++j;
++k;
if (T[j] != T[k])
nextval[j] = k; // j之前的k个字符与开始k个字符相等且0<k<j
else
nextval[j] = nextval[k];
} else {
k = nextval[k];
}
}
}
int kmp_search(char *search, char *pattern, int pos)
{
if (search == NULL || pattern == NULL || pos < 0)
return -1;
int lenS = strlen(search), lenT = strlen(pattern);
std::cout << lenS << " " << lenT << std::endl;
if (pos > lenS || lenS < lenT || lenS - pos < lenT) return -1;
int nextval[lenT];
get_nextval(pattern, nextval);
int i = pos, j = -1;
while (i < lenS && j < lenT) {
if (j == -1 || search[i] == pattern[j]) {
++i;
++j;
} else {
j = nextval[j];
}
}
if (j >= lenT)
return i - lenT;
else
return -1;
}
int main()
{
char sourc[6] = "ababc";
char pattern[4] = "abc";
std::cout << kmp_search(sourc, pattern, 0) << std::endl;
return 0;
}