-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathtrie.cpp
78 lines (77 loc) · 1.63 KB
/
trie.cpp
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
#include <cstdio>
#include <string>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <cstring>
using namespace std;
class TrieNode {
public:
static const int SPACE_SIZE = 26;
TrieNode *children[SPACE_SIZE];
bool exist;
TrieNode() {
for (int i = 0; i < SPACE_SIZE; ++i) {
children[i] = nullptr;
}
exist = false;
}
};
class WordDictionary {
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(const string s) {
TrieNode *p = root;
for (char c : s) {
int index = c - 'a';
if (p->children[index] == nullptr) {
p->children[index] = new TrieNode();
}
p = p->children[index];
}
p->exist = true;
}
void insert(const string s) {
addWord(s);
}
bool search(const string key) const {
return search(root, key.c_str());
}
private:
TrieNode *root;
bool search(TrieNode *p, const char *target) const {
if (p == nullptr)
return false;
int len = strlen(target);
if (target == nullptr || len == 0) {
return p->exist;
}
char c = *target;
if (c != '.') {
int index = c - 'a';
return search(p->children[index], target + 1);
} else {
for (int i = 0; i < TrieNode::SPACE_SIZE; ++i) {
if (search(p->children[i], target + 1))
return true;
}
return false;
}
}
};
int main(int argc, char **argv)
{
WordDictionary trie;
trie.insert("bad");
trie.insert("dad");
trie.insert("mad");
cout << trie.search("") << endl;
cout << trie.search("pad") << endl;
cout << trie.search("bad") << endl;;
cout << trie.search(".ad") << endl;
cout << trie.search("b..") << endl;
cout << trie.search("mada") << endl;
return 0;
}