Implement Trie (Prefix Tree)

解题思路

优化方法有:

  1. 不适用 unordered_map 存储子节点,而是用大小为 26 的数组;
  2. 将搜索过程单独提出来,优化代码结构

代码

class Trie {
public:
    
    struct Node {
        char letter;
        int count;
        unordered_map<char, Node*> childs;
        
        Node() : count(0) {}
        Node(char c) : count(0), letter(c) {}
    };
    /** Initialize your data structure here. */
    Trie() {
         head = new Node();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        if (word.empty()) {
            return;
        }
        Node* curr = head;
        for (char c : word) {
            if (curr->childs.find(c) == curr->childs.end()) {
                Node* next = new Node(c);
                curr->childs[c] = next;
            }
            curr = curr->childs[c];
        }
        curr->count++;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        if (word.empty()) {
            return true;
        }
        Node* curr = head;
        for (char c : word) {
            if (curr->childs.find(c) == curr->childs.end()) {
                return false;
            }
            curr = curr->childs[c];
        }
        return (curr->count > 0)? true: false;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        if (prefix.empty()) {
            return true;
        }
        Node* curr = head;
        for (char c : prefix) {
            if (curr->childs.find(c) == curr->childs.end()) {
                return false;
            }
            curr = curr->childs[c];
        }
        return true;
    }
private:
    Node* head;
};

/**
 * 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);
 */