-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
trie.h
125 lines (109 loc) · 2.3 KB
/
trie.h
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
113
114
115
116
117
118
119
120
121
122
123
124
125
/*******************************************************************************
* DANIEL'S ALGORITHM IMPLEMENTAIONS
*
* /\ | _ _ ._ o _|_ |_ ._ _ _
* /--\ | (_| (_) | | |_ | | | | | _>
* _|
*
* Trie (Prefix tree)
*
* http://en.wikipedia.org/wiki/Trie
******************************************************************************/
#ifndef ALGO_TRIE_H__
#define ALGO_TRIE_H__
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
namespace alg {
const int NUMWORD = 26;
class Trie {
private:
class node {
public:
int words;
int prefixes;
node *edges[NUMWORD];
node():words(0),prefixes(0) {
memset(edges, 0, sizeof(edges));
}
~node() {
for (int i=0;i<NUMWORD;i++) {
if (edges[i] != NULL) {
delete edges[i];
}
}
}
};
node *m_root;
public:
Trie() {
m_root = new node;
}
~Trie() {
delete m_root;
m_root=NULL;
}
void Add(char * str) {
_lowercase(str);
_add(m_root, str);
}
int Count(const char *str) {
char * _str = strdup(str);
_lowercase(_str);
int cnt = _count(m_root, _str);
free(_str);
return cnt;
}
int CountPrefix(const char *prefix) {
char * _str = strdup(prefix);
_lowercase(_str);
int cnt = _count_prefix(m_root, _str);
free(_str);
return cnt;
}
private:
void _lowercase(char *str) {
int i;
for (i=0;str[i];i++) {
str[i] = tolower(str[i]);
}
}
void _add(node *n, const char * str) {
if (str[0] == '\0') {
n->words++;
} else {
n->prefixes++;
int index=str[0]-'a';
if (n->edges[index]==NULL) {
n->edges[index] = new node;
}
_add(n->edges[index], ++str);
}
}
int _count(node *n, const char * str) {
if (str[0] == '\0') {
return n->words;
} else {
int index=str[0]-'a';
if (n->edges[index]==NULL) {
return 0;
}
return _count(n->edges[index], ++str);
}
}
int _count_prefix(node *n, char * str) {
if (str[0] == '\0') {
return n->prefixes;
} else {
int index=str[0]-'a';
if (n->edges[index]==NULL) {
return 0;
}
return _count_prefix(n->edges[index], ++str);
}
}
};
}
#endif //