implement a trie with insert, search, and startsWith methods.
參考的解決方法來源
Note:
a-z
.class TrieNode {
public:
bool isKey;
TrieNode* children[26];
TrieNode(): isKey(false) {
memset(children, NULL, sizeof(TrieNode*) * 26);
}
};
它的優點是:利用字符串的公共前綴來減少查詢時間,最大限度地減少無謂的字符串比較,查詢效率比哈希樹高。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");