211. Add and Search Word - Data structure design

问题描述:

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

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

Note:
You may assume that all words are consist of lowercase letters a-z.

 

解题思路:

看到添加单词,并且搜索首先想到了TrieTree

这里需要注意的是,由于'.'可以代表任何字母,所以这里我们需要进行一个dfs对每一个字母进行尝试。

 

代码:

class TrieNode{
public:
    bool isWord;
    TrieNode *child[26];
    TrieNode(): isWord(false){
        for(auto & a: child){
            a = NULL;
        }
    }
};
class WordDictionary {
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        root = new TrieNode();
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        TrieNode *cur = root;
        for(char c : word){
            int i = c - 'a';
            if(!cur->child[i])
                cur->child[i] = new TrieNode();
            cur = cur->child[i];
        }
        cur->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) {
        return dfs(word, 0, root);
    }
    
    bool dfs(string &w, int idx, TrieNode* node){
        if(idx == w.size()){
            if(node->isWord) return true;
            return false;
        }
        TrieNode *cur = node;
        for(int i = idx; i < w.size(); i++){
            if(w[i] == '.'){
                for(auto a : cur->child){
                    if(a && dfs(w, i+1, a))
                        return true;
                }
                return false;
            }
            if(cur->child[w[i]-'a'])
                cur = cur->child[w[i] - 'a'];
            else
                return false;
        }
        return cur->isWord;
    }
private:
    TrieNode* root;
};

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

 

posted @ 2018-07-20 08:25  妖域大都督  阅读(116)  评论(0编辑  收藏  举报