implement a trie with insert, search, and startsWith methods.
参考的解决方法来源
Note:
You may assume that all inputs are consist of lowercase letters
a-z
.
数据结构的定义
class TrieNode {
public:
bool isKey;
TrieNode* children[26];
TrieNode(): isKey(false) {
memset(children, NULL, sizeof(TrieNode*) * 26);
}
};
它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希
树高。
iskey是用来标记是否从根节点(root)到当前节点node所组成的字符串是否是一个关键字(一整个单词是否被添加)
在这个问题中,只考虑小写字符,因此每个节点最多有26的子节点;将其存储在TrieNode *children[26];其中数组对应的字符是 i+'a'
class TrieNode {
public:
// Initialize your data structure here.
bool iskey;
TrieNode *children[26];
TrieNode():iskey(false) {
memset(children, NULL, sizeof(TrieNode*)*26);
}
};
class Trie {
public:
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++) {
if(p->children[word[i]-'a']==NULL){
p->children[word[i]-'a']=new TrieNode();
}
p=p->children[word[i]-'a'];
}
p->iskey=true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *p=root;
for(int i=0;i<word.size()&&p!=NULL;i++) {
p=p->children[word[i]-'a'];
}
return p&&p->iskey;
}
// 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()&&p!=NULL;i++) {
p=p->children[prefix[i]-'a'];
}
return p;
}
private:
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");