数据结构系列10 - 字符串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
/*************************************************************************
* File Name: kmp.c
* Author: TyrantLucifer
* E-mail: TyrantLucifer@gmail.com
* Blog: https://tyrantlucifer.com
* Created Time: Thu 01 Apr 2021 08:15:11 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysmacros.h>

typedef struct String {
char* data;
int len;
}String;

String* initString() {
String* s = (String*)malloc(sizeof(String));
s->data = NULL;
s->len = 0;
return s;
}

void stringAssign(String* s, char* data) {
if (s->data) {
free(s->data);
}
int len = 0;
char* temp = data;
while (*temp) {
len++;
temp++;
}
if (len == 0) {
s->data = NULL;
s->len = 0;
}
else {
temp = data;
s->len = len;
s->data = (char*)malloc(sizeof(char) * (len + 1));
for (int i = 0; i < len; i++, temp++) {
s->data[i] = *temp;
}
}
}

void printString(String* s) {
for (int i = 0; i < s->len; i++) {
printf(i == 0 ? "%c " : "-> %c ", s->data[i]);
}
printf("\n");
}

int* getNext(String* s) {
int* next = (int*)malloc(sizeof(int) * s->len);
int i = 0;
int j = -1;
next[i] = j;
while (i < s->len - 1) {
if (j == -1 || s->data[i] == s->data[j]) {
i++;
j++;
next[i] = j;
}
else {
j = next[j];
}
}
return next;
}

void printNext(int* next, int len) {
for (int i = 0; i < len; i++) {
printf(i == 0 ? "%d " : "-> %d ", next[i] + 1);
}
printf("\n");
}

void kmpMatch(String* master, String* sub, int* next) {
int i = 0;
int j = 0;
while (i < master->len && j < sub->len) {
if (j == -1 || master->data[i] == sub->data[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
if (j == sub->len) {
printf("kmp match success.\n");
}
else {
printf("kmp match fail.\n");
}
}

int main(int argc, char* argv[])
{
String* s = initString();
String* s1 = initString();
stringAssign(s, argv[1]);
printString(s);
stringAssign(s1, argv[2]);
printString(s1);
int* next = getNext(s1);
printNext(next, s1->len);
kmpMatch(s, s1, next);
return 0;
}