LintCode-442: Implement Trie Prefix Tree (System Design题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/81702585

经典的Trie设计题。
注意
1)因为都是小写字母,所以节点上不需要map,直接开一个26叉的vector指针数组即可。
2)如果Trie用于字符串检索,那Node上带一个bool表示这个到这个节点有一个完整的word。
如果Trie用于词频统计,那Node上带一个int count 表示该节点代表的单词个数,即当这个节点有一个完整的word时,该count自加1。若该word不存在,插入后该word的count置为1。
另外,这两种场合都可以用hashmap来实现。

class Node {
public:
    Node() : isWord(false) {
        children = vector<Node *>(26, nullptr);
    }

    bool isWord;
    vector<Node*> children;
};

class Trie {
public:
    Trie() {
        root = new Node();
    }

    /*
     * @param word: a word
     * @return: nothing
     */
    void insert(string &word) {
        Node *p = root;

        for (int i = 0; i < word.size(); ++i) {
            if (p->children[word[i] - 'a'] == nullptr) {
                p->children[word[i] - 'a'] = new Node();
            }

            p = p->children[word[i] - 'a'];  
        }

        p->isWord = true;    
    }

    /*
     * @param word: A string
     * @return: if the word is in the trie.
     */
    bool search(string &word) {
        Node *p = root;
        for (int i = 0; i < word.size(); ++i) {
            if (p->children[word[i] - 'a'] == nullptr)
                return false;
            p = p->children[word[i] - 'a'];    
        }

        if (p->isWord) return true;
        else return false;
    }

    /*
     * @param prefix: A string
     * @return: if there is any word in the trie that starts with the given prefix.
     */
    bool startsWith(string &prefix) {
        Node *p = root;
        for (int i = 0; i < prefix.size(); ++i) {
            if (p->children[prefix[i] - 'a'] == nullptr)
                return false;
            p = p->children[prefix[i] - 'a'];    
        }
        return true;       
     }

private: 
    Node* root;
};

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/81702585