-
Notifications
You must be signed in to change notification settings - Fork 30
/
kmp.c
142 lines (132 loc) · 2.43 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/**
* @file kmp.c
* @author hutusi ([email protected])
* @brief Refer to kmp.h
* @date 2019-08-07
*
* @copyright Copyright (c) 2019, hutusi.com
*
*/
#include "kmp.h"
#include "def.h"
#include <stdlib.h>
#include <string.h>
/**
* @brief Calculate next array
*
* calucate the max matched suffix substring' length.
*
* string: abcdabd
*
* a 0
* ab 0
* abc 0
* abcd 0
* abcda 1
* abcdab 2
* abcdabd 0
*
* string: ababa
*
* a 0
* ab 0
* aba 1
* abab 2
* ababa 3
*
* @param string
* @param len
* @return STATIC* kmp_calculate_next
*/
STATIC int *kmp_calculate_next(const char *string, int len)
{
int *next = (int *)calloc(len, sizeof(int));
next[0] = 0;
int k = 0;
for (int i = 1; i < len; ++i) {
while (k > 0 && string[k] != string[i]) {
k = next[k];
}
if (string[k] == string[i]) {
++k;
}
next[i] = k;
}
return next;
}
/**
* @brief KMP algorithm
*
* text: bbcabcdababcdabcdabde
* pattern: abcdabd
*
* !
* bbcabcdababcdabcdabde
* abcdabd
*
* step 1 ->
* !
* bbcabcdababcdabcdabde
* abcdabd
*
* step 1 ->
* !
* bbcabcdababcdabcdabde
* abcdabd
*
* step 1 ->
* !
* bbcabcdababcdabcdabde
* abcdabd
*
* step 1 -> ... until find failure charactor 'a'-'d'
* ! *
* bbcabcdababcdabcdabde
* abcdabd
*
* step next[5] = 4, then step 1... until find failure charactor 'a'-'c'
* ! *
* bbcabcdababcdabcdabde
* abcdabd
*
* step next[3] = 2 ...
* !
* bbcabcdababcdabcdabde
* abcdabd
*
* ......
*
* @param text
* @param pattern
* @return int
*/
int kmp_text_match(const char *text,
unsigned int text_len,
const char *pattern,
unsigned int pat_len)
{
int *next = kmp_calculate_next(pattern, pat_len);
int index = -1;
int j = 0;
for (int i = 0; i < text_len; ++i) {
if (text[i] == pattern[j]) {
++j;
} else {
if (j > 0) {
/** C allowed n[-1] */
j = next[j - 1];
--i;
}
}
if (j >= pat_len) {
index = i + 1 - pat_len;
break;
}
}
free(next);
return index;
}
int kmp_string_match(const char *text, const char *pattern)
{
return kmp_text_match(text, strlen(text), pattern, strlen(pattern));
}