面试经典150题 P208 实现Trie(前缀树)
时间轴
2025-11-24
init
题目:
前缀树实现,注意必须要有is_end,这样才能判断是否为一个单词的结尾。
其实可以直接用vector存,因为只有26个字母,把字母转为数字即可。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
using std::vector;
using std::string;
using std::unordered_map;
typedef struct TrieNode {
//vector<struct TrieNode *> children;
unordered_map<char, struct TrieNode *> children;
char data;
bool is_end;
} TrieNode;
class Trie {
private:
TrieNode *root;
public:
Trie()
{
root = new TrieNode;
root->children = unordered_map<char, TrieNode *>();
root->is_end = false;
}
void insert(string word)
{
TrieNode *p = root, *node;
int i = 0, n = word.size();
char ch;
for (i = 0; i < n; i++) {
ch = word[i];
if (p->children.count(ch)) {
p = p->children[ch];
if (i == n - 1) {
p->is_end = true;
}
continue;
}
node = new TrieNode;
node->children = unordered_map<char, TrieNode *>();
node->data = ch;
if (i == n - 1) {
node->is_end = true;
} else {
node->is_end = false;
}
p->children[ch] = node;
p = node;
}
}
bool search(string word)
{
int i, n = word.size();
char ch;
TrieNode *p = root;
for (i = 0; i < n; i++) {
ch = word[i];
if (p->children.count(ch)) {
p = p->children[ch];
continue;
}
return false;
}
return p->is_end;
}
bool startsWith(string prefix)
{
int i, n = prefix.size();
char ch;
TrieNode *p = root;
for (i = 0; i < n; i++) {
ch = prefix[i];
if (p->children.count(ch)) {
p = p->children[ch];
continue;
}
return false;
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/





