【Leetcode208】Implement Trie (Prefix Tree)

方法一:

笨方法,搞两个unordered_set保存所有的word和word的prefix,可以通过,但是时间复杂度太高了;

方法二:

字典树,重在如何抽象出树的node 

class TrieNode{
public:
    bool isWord;
    TrieNode* children[26];
    TrieNode(){
        isWord = false;
        for(auto& p : children){
            p = nullptr;//必须初始化,避免成为野指针
        }
    }
};
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* p = root;//临时节点,用于循环
        for(size_t index = 0; index < word.size(); ++index){
            size_t current = word[index]-'a';
            if(p->children[current] == nullptr){
                p->children[current] = new TrieNode;//不要总想着一次把所有的新节点都创建出来,分解成循环的子问题
            }
            p = p->children[current];
        }
        p->isWord = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode* p = root;
        for(size_t index = 0; index < word.length(); ++index){
            size_t current = word[index] - 'a';
            if(p->children[current] == nullptr)
                return false;
            p = p->children[current];
        }
        return p->isWord;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        TrieNode* p = root;
        for(size_t index = 0; index < prefix.length(); ++index){
            size_t current = prefix[index] - 'a';
            if(p->children[current] == nullptr)
                return false;
            p = p->children[current];
        }
        return true;
    }
};

 

发布了118 篇原创文章 · 获赞 16 · 访问量 2万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览