-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.c
69 lines (64 loc) · 1.99 KB
/
Trie.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
/*************************************************************************
> File Name: trie.c
> Author: snowflake
> Mail: ︿( ̄︶ ̄)︿
> Created Time: 2018年08月09日 星期四 15时05分22秒
************************************************************************/
#include "HF_Trie.h"
Node *get_trie_node() {
Node *p = (Node *)calloc(sizeof(Node), 1);
node_cnt += 1;
return p;
}
void clear(Trie node) {
if (node == NULL) return ;
for (int i = 0; i < BASE; i++) {
if (node->next[i] == NULL) continue;
clear(node->next[i]);
}
if (node->flag) free(node->str);
free(node);
return ;
}
Node *insert(Trie root, const unsigned char *pattern) {
if (root == NULL) root = get_trie_node();
Node *p = root;
int len = strlen((char *)pattern);
for (int i = 0; i < len - 2; i++) {
char temp[100] = {0};
strncpy(temp, (char *)hftable[pattern[i]], strlen((char *)hftable[pattern[i]]));
for (int j = 0; temp[j]; j++) {
int ind = temp[j] - BL;
if (p->next[ind] == NULL) p->next[ind] = get_trie_node();
p = p->next[ind];
}
memset(temp, 0, 10);
}
p->flag = 1;
p->str = strdup((char *)pattern);
printf("%s", p->str);
return root;
}
void search(Trie root, const unsigned char *text) {
Node *p = root;
int len = strlen((char *)text);
unsigned char *text_temp = (unsigned char *)calloc(sizeof(unsigned char), len * 10);
for (int i = 0; text[i]; i++) {
strncat((char *)text_temp, (char *)hftable[text[i]], strlen((char *)hftable[text[i]]));
}
for (int i = 0; text_temp[i]; i++) {
int j = i;
p = root;
while (text_temp[j] && p && p->next[text_temp[j] - BL]) {
search_times++;
p = p->next[text_temp[j] - BL];
if (p->flag == 1) {
printf("find word : %s", p->str);
break;
}
j++;
}
}
free(text_temp);
return ;
}