LeetCode——208. Implement Trie (Prefix Tree)
阿新 • • 發佈:2019-02-12
Description
Implement a trie with insert, search, and startsWith methods.
Example
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true
Note
- You may assume that all inputs are consist of lowercase letters a-z.
- All inputs are guaranteed to be non-empty strings.
Solution 1(C++)
class TrieNode{
public:
staic const int NODE_SIZE = 26;
TrieNode* child[NODE_SIZE];
bool isExist;
TrieNode(){
for(int i=0; i<NODE_SIZE; i++){
child[ i] = NULL;
}
isExist = false;
}
TrieNode(char c){
for(int i=0; i<NODE_SIZE; i++){
if(c-'a' == i) child[i] = new TrieNode();
}
isExist = false;
}
};
class Trie{
public:
Trie(){
root = new TrieNode();
root->isExist = true;
}
~Trie(){
Destory(node);
}
void insert(string word) {
TrieNode* temp = root;
for(int i=0; i<word.size(); i++){
if(temp->child[word[i]-'a'] == NULL){
temp->child[word[i]-'a'] = new TrieNode();
}
temp = temp->child[word[i]-'a'];
}
temp->isExist = true;
}
bool search(string word){
if(word == "") return true;
TrieNode* temp = root;
for(int i=0; i<word.size(); i++){
if(temp->child[word[i]-'a'] == NULL) return false;
temp = temp->child[word[i]-'a'];
}
return temp != NULL && temp->isExist == true;
}
bool startsWith(string prefix){
if(prefix == "") return true;
TrieNode* temp = root;
for(int i=0; i<prefix.size(); i++){
if(temp->child[prefix[i]-'a'] == NULL) return false;
temp = temp->child[prefix[i]-'a'];
}
return temp != NULL;
}
void Destory(TreeNode* node)}{
for(int i=0; i<NODE_SIZE; I++){
if(node->child[i] == NULL) Destory(node->child[i]);
}
}
private:
TrieNode* root;
};
演算法分析
這道題考察的是字典樹。弄明白字典樹的基本含義,這道題目就不難。
程式分析
注意,雖然對解題沒有什麼幫助,但是還要注意,解構函式與記憶體的釋放。養成一個好習慣,畢竟用了C++。