- Implement Trie (Prefix Tree)
中文English
Implement a Trie with insert, search, and startsWith methods.
Example
Example 1:
Input:
insert(“lintcode”)
search(“lint”)
startsWith(“lint”)
Output:
false
true
Example 2:
Input:
insert(“lintcode”)
search(“code”)
startsWith(“lint”)
startsWith(“linterror”)
insert(“linterror”)
search("lintcode“)
startsWith(“linterror”)
Output:
false
true
false
true
true
Notice
You may assume that all inputs are consist of lowercase letters a-z.
经典的Trie设计题。
注意
1)因为都是小写字母,所以节点上不需要map,直接开一个26叉的vector指针数组即可。
2)如果Trie用于字符串检索,那Node上带一个bool表示这个到这个节点有一个完整的word。
如果Trie用于词频统计,那Node上带一个int count 表示该节点代表的单词个数,即当这个节点有一个完整的word时,该count自加1。若该word不存在,插入后该word的count置为1。
另外,这两种场合都可以用hashmap来实现。
class Node {
public:
Node() : isWord(false) {
children = vector<Node *>(26, nullptr);
}
bool isWord;
vector<Node*> children;
};
class Trie {
public:
Trie() {
root = new Node();
}
/*
* @param word: a word
* @return: nothing
*/
void insert(string &word) {
Node *p = root;
for (int i = 0; i < word.size(); ++i) {
if (p->children[word[i] - 'a'] == nullptr) {
p->children[word[i] - 'a'] = new Node();
}
p = p->children[word[i] - 'a'];
}
p->isWord = true;
}
/*
* @param word: A string
* @return: if the word is in the trie.
*/
bool search(string &word) {
Node *p = root;
for (int i = 0; i < word.size(); ++i) {
if (p->children[word[i] - 'a'] == nullptr)
return false;
p = p->children[word[i] - 'a'];
}
if (p->isWord) return true;
else return false;
}
/*
* @param prefix: A string
* @return: if there is any word in the trie that starts with the given prefix.
*/
bool startsWith(string &prefix) {
Node *p = root;
for (int i = 0; i < prefix.size(); ++i) {
if (p->children[prefix[i] - 'a'] == nullptr)
return false;
p = p->children[prefix[i] - 'a'];
}
return true;
}
private:
Node* root;
};