力扣 211. 添加与搜索单词 - 数据结构设计 字典树

https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/
力扣 211. 添加与搜索单词 - 数据结构设计 字典树_第1张图片
思路:字典树经典题目。看数据范围,暴力比对的话大概率会超时。字典树就是前缀树,支持插入字符串、快速检索字符串 or 前缀是否出现过,当然它还有一些变体存在,比如01字典树等。详见我的这篇博客,此处就不多说了。字符 “.” 其实也挺好处理的,写个深搜嘛。

class TireNode{
public:
    array<TireNode*, 26> children;
    bool isEnd=false;
};

class TireTree{
public:

    TireTree():root(new TireNode()){}

    void insert(const string& word)
    {
        TireNode *cur=root;
        for(char ch: word)
        {
            int idx=ch-'a';
            if(!cur->children[idx])
                cur->children[idx]=new TireNode();
            cur=cur->children[idx];
        }
        cur->isEnd=true;
    }

    bool search(const string& word)
    {
        return _search(word, root);
    }

private:
    TireNode *root;

    bool _search(const string& word,TireNode *cur, int pos=0)
    {
        int siz=word.size();
        if(pos==siz)
            return cur->isEnd;
        int idx=word[pos]-'a';
        if(word[pos]=='.')
        {
            for(int j=0;j<26;j++)
                if(cur->children[j]&&_search(word, cur->children[j], pos+1))
                    return true;
            return false;
        }
        else if(!cur||!cur->children[idx])
            return false;
        else
            return _search(word, cur->children[idx], pos+1);
    }
};

class WordDictionary {
public:
    WordDictionary() {

    }
    
    void addWord(string word) {
        tireTree.insert(word);
    }
    
    bool search(string word) {
        return tireTree.search(word);
    }
private:
    TireTree tireTree;
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */

你可能感兴趣的:(力扣,字典树,搜索,数据结构)