天天看點

[leetcode] 208. Implement Trie (Prefix Tree)

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.

分析

題目的意思是:實作一個字典樹。

Trie樹,又叫字典樹、字首樹(Prefix Tree)、單詞查找樹或鍵樹,是一種多叉樹結構。

[leetcode] 208. Implement Trie (Prefix Tree)

上圖是一棵Trie樹,表示了關鍵字集合{“a”, “to”, “tea”, “ted”, “ten”, “i”, “in”, “inn”} 。從上圖可以歸納出Trie樹的基本性質:

①根節點不包含字元,除根節點外的每一個子節點都包含一個字元。

②從根節點到某一個節點,路徑上經過的字元連接配接起來,為該節點對應的字元串。

③每個節點的所有子節點包含的字元互不相同。

  • 要實作insert,search,startswith函數。unordered_map表類存儲字元和結點的映射,insert方法就是在unordered_map上查找建立的過程。search是map上的周遊過程。startwith也是一樣的查找。

代碼

class TrieNode{
  public:
    unordered_map<char,TrieNode *> children; 
    bool isLeaf;
    TrieNode(){isLeaf = false;};
};

class Trie {
private:
    TrieNode* root;
public:
    /** Initialize your data structure here. */
    Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        TrieNode *cur = root;
        for(int i=0;i<word.size();i++){
            if(cur->children.find(word[i])==cur->children.end()){
                cur->children[word[i]] = new TrieNode();
            }
            cur=cur->children[word[i]];
        }
        cur->isLeaf=true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode *cur = root;
        for(int i=0;i<word.size();i++){
            if(cur->children.find(word[i])==cur->children.end()){
                return false;
            }
            cur=cur->children[word[i]];
        }
        if(cur->isLeaf){
            return true;
        }
        return false;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        TrieNode *cur = root;
        for(int i=0;i<prefix.size();i++){
            if(cur->children.find(prefix[i])==cur->children.end()){
                return false;
            }
            cur=cur->children[prefix[i]];
        }
        return true;
    }
};



/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * bool param_2 = obj.search(word);
 * bool param_3 = obj.startsWith(prefix);
 */      

參考文獻