-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp.cpp
More file actions
49 lines (45 loc) · 671 Bytes
/
Copy pathkmp.cpp
File metadata and controls
49 lines (45 loc) · 671 Bytes
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
#include <iostream>
using namespace std;
void getNext(char *src, int *next, int len)
{
if (src == NULL)
return ;
int i = 0;
int j = -1;
next[i] = 0;
while(i < len - 1)
{
if (j == -1 || src[i] == pattern[j])
{
i++;
j++;
if (src[i] != src[j])
next[i] = j;
else
next[i] = next[j];
} else
{
j = next[j];
}
}
}
int kmp_search(char *src, int src_len, char * pattern, int pattern_len, int pos, int *next)
{
int i = pos;
int j = 0;
while(j < pattern_len && i < src_len)
{
if (j == -1 || src[i] == pattern[j])
{
i++;
j++;
}else
{
j = next[j];
}
}
if (j == pattern_len)
return i - j;
else
return -1;
}