-
Notifications
You must be signed in to change notification settings - Fork 0
/
pre_post_fix.c
112 lines (92 loc) · 2.07 KB
/
pre_post_fix.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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "fix.h"
Fix_S *prefix_postfix_max(const char *s) {
if (NULL == s || 0 == s[0]) {
return NULL;
}
int i;
int *value;
size_t len = strlen(s);
size_t size = len * sizeof(int) + sizeof(Fix_S);
Fix_S *f = (Fix_S *)malloc(size);
if (NULL == f) {
return f;
}
memset(f, 0, size);
f->size = len;
f->value = (int *)(((char *)f) + sizeof(Fix_S));
value = f->value;
for (i = 1; i < len; i++) {
if (s[i] == s[value[i - 1]]) {
value[i] = value[i - 1] + 1;
}
}
return f;
}
Fix_S *prefix_postfix_max_sub(const char *s) {
if (NULL == s || 0 == s[0]) {
return NULL;
}
int i;
int *value;
size_t len = strlen(s);
size_t size = (len + 1) * sizeof(int) + sizeof(Fix_S);
Fix_S *f = (Fix_S *)malloc(size);
if (NULL == f) {
return f;
}
memset(f, 0, size);
f->size = len + 1;
f->value = (int *)(((char *)f) + sizeof(Fix_S));
value = f->value;
for (i = 1; i < len; i++) {
if (s[i] == s[value[i]]) {
value[i + 1] = value[i] + 1;
}
}
return f;
}
static void print_fix(int size, int *f) {
while (size) {
if (size > 1) {
printf("%d, ", *f);
}
else {
printf("%d\n", *f);
}
f++;
size--;
}
}
int kmp_first(const char *src, const char *target) {
int i, j;
int index = -1;
size_t targetLen = strlen(target);
size_t srcLen = strlen(src);
Fix_S *f = prefix_postfix_max_sub(target);
if (NULL == f) {
return index;
}
for (i = 0, j = 0; i < srcLen;) {
if (src[i] != target[j]) {
if (0 == j) {
i++;
}
j = f->value[j];
}
else {
if (j == targetLen - 1) {
index = i - j ;
break;
}
else {
j++;
i++;
}
}
}
free(f);
return index;
}