Leetcode211. Add and Search Word - Data structure design 添加與搜索單詞 - 數據結構設計

設計一個支持如下兩種操做的數據結構:正則表達式

void addWord(word) bool search(word)數據結構

search(word) 能夠搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。 . 能夠表示任何一個字母。設計

示例:code

addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true字符串

說明:string

你能夠假設全部單詞都是由小寫字母 a-z 組成的。it

 

 

典型的字典樹,前綴樹的用法io

 

class WordDictionary {
public:
    struct TrieNode
    {
        TrieNode(): isword(false), children(26, nullptr){}
        ~TrieNode()
        {
            for(TrieNode* child : children)
            {
                if(child)
                    delete child;
            }
        }
        bool isword;
        vector<TrieNode*> children;
    };

    TrieNode* root;

    /** Initialize your data structure here. */
    WordDictionary() : root(new TrieNode()){
        
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        TrieNode *p = root;
        for(char c : word)
        {
            if(p ->children[c - 'a'] == nullptr)
            {
                p ->children[c - 'a'] = new TrieNode();
            }
            p = p ->children[c - 'a'];
        }
        p ->isword = true;
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    bool search(string word) const{
        TrieNode *p = root;
        for(int i = 0; i < word.size(); i++)
        {
            if(word[i] == '.')
            {
                for(int j = 0; j < 26; j++)
                {
                    if(p ->children[j])
                    {
                        if(Find(string(word.begin() + i + 1, word.end()), p ->children[j]))
                            return true;
                    }
                }
                return false;
            }
            else
            {
                p = p ->children[word[i] - 'a'];
                if(p == nullptr)
                    return false;
            }
        }
        if(p ->isword)
            return true;
        return false;
    }

    const bool Find(string word, TrieNode* p) const
    {
        for(int i = 0; i < word.size(); i++)
        {
            if(word[i] == '.')
            {
                for(int j = 0; j < 26; j++)
                {
                    if(p ->children[j])
                    {
                        if(Find(string(word.begin() + i + 1, word.end()), p ->children[j]))
                            return true;
                    }
                }
                return false;
            }
            else
            {
                p = p ->children[word[i] - 'a'];
                if(p == nullptr)
                    return false;
            }
        }
        if(p ->isword)
            return true;
        return false;
    }
};
相關文章
相關標籤/搜索