-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmp.c
73 lines (69 loc) · 1.32 KB
/
kmp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<stdio.h>
#include<string.h>
void getNext(char*, int, int*);
void getNextVal(char*, int, int*);
int kmp(char*, int, char*, int, int*, int);
int main(void)
{
char* s = "aaaaaaaaaaaacdadadcaaaab";
char* subs = "aaaab";
int lens = strlen(s);
int lensubs = strlen(subs);
int next[lensubs];
int nextVal[lensubs];
getNext(subs, lensubs, next);
getNextVal(subs, lensubs, nextVal);
int i;
int pos;
scanf("%d", &pos);
if(pos % 2 == 0)
printf("%d\n", kmp(s, lens, subs, lensubs, next, pos));
else
printf("%d\n", kmp(s, lens, subs, lensubs, nextVal, pos));
return 0;
}
void getNext(char* subs, int lensubs, int* next)
{
next[0] = -1;
int i = 0, j = -1;
while(i < lensubs)
{
if(j == -1 || subs[i] == subs[j])
next[++ i] = ++ j;
else
j = next[j];
}
}
void getNextVal(char* subs, int lensubs, int* nextVal)
{
nextVal[0] = -1;
int i = 0, j = -1;
while(i < lensubs)
{
if(j == -1 || subs[i] == subs[j])
{
i++, j++;
if(subs[i] != subs[j])
nextVal[i] = j;
else
nextVal[i] = nextVal[j];
}
else
j = nextVal[j];
}
}
int kmp(char* s, int lens, char* subs, int lensubs, int* nextPos, int pos)
{
int i = pos - 1, j = -1;
while(i < lens && j < lensubs)
{
if(j == -1 || s[i] == subs[j])
i ++, j ++;
else
j = nextPos[j];
}
if(j >= lensubs)
return i - lensubs;
else
return -1;
}