思路
这一题的关键在于树的节点如何实现。
我这里采用isWord表示到达该节点的路径是否组成单词。例如,插入单词appple后,节点e的isWord变量为true,第二个p的isWord为false。接着再插入单词app,则第二个p的isWord改为true即可。
通过一个拥有26个元素的vector保存子节点。在构造函数中,全部初始化为nullptr。在析构函数中,将非nullptr节点删除。
代码
struct TrieNode {
bool isWord;
vector<TrieNode*> next;
TrieNode(): isWord(false), next(26, nullptr) { }
~TrieNode() {
for (auto &node : next)
if (node) {
delete node;
node = nullptr;
}
}
};
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *p = root;
for (int i = 0; i < word.size(); ++i) {
int oft = word[i] - 'a';
if (!p->next[oft])
p->next[oft] = new TrieNode();
p = p->next[oft];
}
p->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p = root;
for (int i = 0; i < word.size(); ++i) {
int oft = word[i] - 'a';
if (!p->next[oft])
return false;
p = p->next[oft];
}
return p->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *p = root;
for (int i = 0; i < prefix.size(); ++i) {
int oft = prefix[i] - 'a';
if (!p->next[oft])
return false;
p = p->next[oft];
}
return true;
}
~Trie() { delete root; }
private:
TrieNode *root;
};
/**
* 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);
*/