数据结构系列9-字符串暴力匹配

数据结构系列9 - 字符串暴力匹配 - 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
/*************************************************************************
* File Name: forceMatch.c
* Author: TyrantLucifer
* E-mail: TyrantLucifer@gmail.com
* Blog: https://tyrantlucifer.com
* Created Time: Wed 31 Mar 2021 12:04:47 AM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.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");
}

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

int main(int argc, char* argv[])
{
String* s = initString();
String* s1 = initString();
stringAssign(s, argv[1]);
stringAssign(s1, argv[2]);
printString(s);
printString(s1);
forceMatch(s, s1);
return 0;
}

数据结构系列9-字符串暴力匹配

https://tyrantlucifer.com/33.html

发布于

2021-07-01

更新于

2021-07-01

许可协议

评论

:D 一言句子获取中...