Fork me on GitHub

Leetcode211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计

设计一个支持以下两种操作的数据结构:

void addWord(word) bool search(word)

search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。

示例:

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

说明:

你可以假设所有单词都是由小写字母 a-z 组成的。

 

 

典型的字典树,前缀树的用法

 

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;
    }
};

 

posted @ 2019-01-17 17:26  lMonster81  阅读(231)  评论(0编辑  收藏  举报
/*评论*/ /*top按钮*/

/* 网易云控件 */