您的位置:首页 > 编程语言 > C语言/C++

Leetcode——208. Implement Trie (Prefix Tree) C++语言实现Tire

2017-09-06 16:25 1141 查看
//slower than recursive version
class Trie {
private:
static constexpr int R = 26;
struct Node {
bool is_word = false;
Node *next = nullptr;
};
public:
//~Trie(); How to write efficient dectructor?
void insert(string word) {
if (word.empty()) return;
Node *x = &root;
int p = 0;
while (p < word.size()) {
if (!x->next) x->next = new Node[R];
x = &x->next[word[p++] - 'a'];
}
x->is_word = true;
}
bool search(string word) {
Node x = root;
int p = 0;
while (x.next && p < word.size())
x = x.next[word[p++] - 'a'];
return p == word.size() && x.is_word;
}
bool startsWith(string prefix) {
Node x = root;
int p = 0;
while (x.next && p < prefix.size())
x = x.next[prefix[p++] - 'a'];
return p == prefix.size() && (x.next || x.is_word);
}
private:
Node root;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: