Implement a trie with insert, search,
and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
基本思路,
作一个26叉树。
本来想作一个27叉,用额外一叉,表示字符串的结束字符(‘\0‘). 但感觉此法浪费内存。后增加一个标志isword,来表示第27叉。
根结点,不表示任何字符。
当前节点所代表的字符位于父结点的分叉中。
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() : childs(26), isword(false) {
}
TrieNode *get(char ch, bool create = false) {
const int index = ch - 'a';
if (create && !childs[index]) {
childs[index] = new TrieNode();
}
return childs[index];
}
bool isword;
private:
vector<TrieNode *> childs;
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
auto t = root;
for (auto ch: word) {
t = t->get(ch, true);
}
t->isword = true;
}
// Returns if the word is in the trie.
bool search(string word) {
auto t = find(word);
return t && t->isword;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
return !!find(prefix);
}
private:
TrieNode *find(string word) {
auto t = root;
for (auto ch: word) {
if (!(t = t->get(ch)))
break;
}
return t;
}
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");版权声明:本文为博主原创文章,未经博主允许不得转载。
Implement Trie (Prefix Tree) -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/47209923