Scott's world.

KMP

Word count: 253Reading time: 1 min
2019/07/05 Share

KMP

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int ViolentMatch(char * s,char * p)
{
int sLength=strlen(s);
int pLength=strlen(p);

int i,j;
i=0;j=0;

while(i<sLength && j<pLength)
{
if(*(s+i)==*(p+j))
{
i++;
j++;
}
else
{
i=i-j+1;
j=0;
}
}
if(j==pLength)
{
return i-j;
}
return 0;
}
int KMP(char *s,char *p)
{
int i=0;
int j=0;
int pLength=strlen(p);
int sLength=strlen(s);
int * next;
next=(int *)malloc(pLength * sizeof(int));
GetNext(p,next);
while(i<sLength && j<pLength)
{
if(j==-1||*(s+i)==*(p+j))
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j==pLength)
{
return i-j;
}
return 0;
}
void GetNext(char * p,int next[])
{
int j=0;
int length=strlen(p);
next[0]=-1;
int k=-1;
while(j<length-1)
{
if(k==-1||*(p+j)==*(p+k))
{
j++;
k++;
if(*(p+j)!=*(p+k))
{
next[j]=k;
}
else
{
next[j]=next[k];
}
}
else
{
k=next[k];
}
}
}
int main()
{
printf("Hello world!\n");
char s[10]={"hello"};
char p[10]={"lloo"};
if(ViolentMatch(s,p))
{
printf("Find it!\n");
}
if(KMP(s,p))
{
printf("Find it!\n");
}
return 0;
}
CATALOG
  1. 1. KMP