#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
void getNext(const char *s,int *next,const int len)
{
next[0] = -1;
next[1] = 0;
int i = 2;
int k = 0;
for (; i < len;)
{
if (k==-1||s[k] == s[i - 1])
{
next[i] = k + 1;
i++;
k++;
}
else
{
k = next[k];
}
}
}
void getNextval(const char* s, const int* next, const int len, int* nextval)
{
nextval[0] = -1;
int i = 1;
for (; i < len; i++)
{
if (s[next[i]] == s[i])
{
nextval[i] = next[next[i]];
}
else
{
nextval[i] = next[i];
}
}
}
int KMP(const char* s1, const char* s2, int pos)
{
assert(s1 && s2);
int len1 = strlen(s1);
int len2 = strlen(s2);
if (len1 == 0 || len2 == 0)
return -1;
if (pos < 0 || pos >= len1)
return -1;
int* next = (int*)malloc(sizeof(int) * len2);
getNext(s1,next,len2);
int* nextval = (int*)malloc(sizeof(int) * len2);
getNextval(s1,next,len2,nextval);
int i = pos; int j = 0;
while (i < len1 && j < len2)
{
if (j == -1 || s1[i] == s2[j])
{
i++;
j++;
}
else
{
j = nextval[j];
}
}
if (j >= len2)
return i - j;
return -1;
}
int main()
{
char str1[] = "adsadjdj";
char str2[] = "djd";
int pos = 0;
int k = KMP(str1, str2,0);
printf("%d", k);
return 0;
}