-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubstr_kmp.c
More file actions
39 lines (30 loc) · 844 Bytes
/
substr_kmp.c
File metadata and controls
39 lines (30 loc) · 844 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
#include <stddef.h>
#include <string.h>
#include "substr.h"
const char *find_substr( const char *text
, const char *pattern
, bool (*eq)(char,char) ) {
int T[(strlen(pattern)+1) * sizeof(int)];
int i, j;
const char *result = 0;
T[0] = -1;
if (pattern[0] == '\0')
return text;
for (i=0; pattern[i] != '\0'; i++) {
T[i+1] = T[i] + 1;
while (T[i+1] > 0 && !eq(pattern[i], pattern[T[i+1]-1]) )
T[i+1] = T[T[i+1]-1] + 1;
}
/* Perform the search */
for (i=j=0; text[i] != '\0'; ) {
if (j < 0 || eq(text[i], pattern[j]) ) {
++i, ++j;
if (pattern[j] == '\0') {
result = text+i-j;
break;
}
}
else j = T[j];
}
return result;
}