实现
Trie树最有优势的是查找前缀匹配的字符串,比如搜索引擎中的关键词提示功能这个场景
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
m_root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* p = m_root;
for (char c : word) {
if (p->children[c - 'a'] == nullptr) {
p->children[c - 'a'] = new TrieNode();
}
p = p->children[c - 'a'];//下移
}
p->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* ret = find(word);
return ret != nullptr && ret->isWord == true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* ret = find(prefix);
return ret != nullptr;
}
private:
struct TrieNode{
//构造
TrieNode() : isWord(false), children(26, nullptr) {}
~TrieNode()
{
for (TrieNode* n : children) {
if (n) {
delete n;
}
}
}
bool isWord;
vector<TrieNode*> children;
};
TrieNode* find(const string& prefix)
{
TrieNode* p = m_root;
for (char c : prefix) {
p = p->children[c - 'a'];
if (p == nullptr) {
break;
}
}
return p;
}
TrieNode* m_root;
};