-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathKMP 串的模式匹配 match[i]表示pattern首尾匹配子串的最大长度.c
72 lines (62 loc) · 1.5 KB
/
KMP 串的模式匹配 match[i]表示pattern首尾匹配子串的最大长度.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
/**
* 针对讨论KMP.3 match[j] 的另一种定义的实现
*
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRINGLENGTH 1000000
#define PATTERNLENGTH 100000
typedef int Position;
#define NotFound -1
void BuildMatch(char *pattern, int *match);
Position KMP(char *string, char *pattern);
int main()
{
char string[STRINGLENGTH + 1];
char pattern[PATTERNLENGTH + 1];
int N, i;
Position p;
scanf("%s", string);
scanf("%d", &N);
for (i = 0; i < N; ++i) {
scanf("%s", pattern);
p = KMP(string, pattern);
if (p == NotFound) printf("Not Found\n");
else printf("%s\n", string + p);
}
return 0;
}
void BuildMatch(char *pattern, int *match)
{
Position i, j;
int m = strlen(pattern);
match[0] = 0;
for (j = 1; j < m; ++j) {
i = match[j - 1];
while ((i > 0) && (pattern[i] != pattern[j]))
i = match[i - 1];
if (pattern[i] == pattern[j])
match[j] = i + 1;
else match[j] = 0;
}
}
Position KMP(char *string, char *pattern)
{
int n = strlen(string);
int m = strlen(pattern);
Position s, p, *match;
if (n < m) return NotFound;
match = (Position *)malloc(sizeof(Position) * m);
BuildMatch(pattern, match);
s = p = 0;
while (s < n && p < m) {
if (string[s] == pattern[p]) {
++s; ++p;
}
else if (p > 0) p = match[p - 1];
else ++s;
}
free(match);
return (p == m) ? (s - m) : NotFound;
}