LeetCode 208 Implement Trie (Prefix Tree)
概述
https://leetcode.com/problems/implement-trie-prefix-tree/
基于多叉树的前缀树实现
注意指针数组要初始化,否则:member access within misaligned address
class Trie {
public:
class Node {
public:
Node* children[26];
bool end = false;
Node() : children() {}
};
Node* root;
Trie() {
root = new Node;
}
void insert(string word) {
auto node = root;
for (auto c : word) {
if (!node->children[c - 'a']) {
node->children[c - 'a'] = new Node;
}
node = node->children[c - 'a'];
}
node->end = true;
}
bool search(string word) {
auto node = root;
for (auto c : word) {
if (node->children[c - 'a']) {
node = node->children[c - 'a'];
} else {
cout << endl;
return false;
}
}
return node->end;
}
bool startsWith(string prefix) {
auto node = root;
for (auto c : prefix) {
if (node->children[c - 'a']) {
node = node->children[c - 'a'];
} else {
return false;
}
}
return true;
}
};