LeetCode 208. 实现 Trie (前缀树)
原题链接
中等
作者:
回归线
,
2021-04-14 21:36:53
,
所有人可见
,
阅读 269
class Trie {
struct Node {
Node* son[26];
bool is_end;
};
Node* root;
public:
/** Initialize your data structure here. */
Trie() {
root = new Node();
}
/** Inserts a word into the trie. */
void insert(string word) {
Node* p = root;
for (char c: word) {
const int t = c - 'a';
if (!p->son[t]) {
p->son[t] = new Node();
}
p = p->son[t];
}
p->is_end = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Node* p = root;
for (char c: word) {
const int t = c - 'a';
if (!p->son[t]) {
return false;
}
p = p->son[t];
}
return p->is_end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Node* p = root;
for (char c: prefix) {
const int t = c - 'a';
if (!p->son[t]) {
return false;
}
p = p->son[t];
}
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);
*/