leetcode@ [211] Add and Search Word - Data structure design

https://leetcode.com/problems/add-and-search-word-data-structure-design/

本题是在Trie树进行dfs+backtracking操作。

Trie树模板代码见:http://www.cnblogs.com/fu11211129/p/4952255.html

 

题目介绍:

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.

For 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.

 

struct Trie{
    Trie *next[26]; //include character '.'
    bool isWord;
    Trie() {
        for(auto &n : this->next) n = NULL;
        this->isWord = false;
    }
};
class WordDictionary {
public: 
    Trie *root;
    WordDictionary() {
        this->root = new Trie();
    }

    void insert(string s) {
        Trie *p = this->root;
        for(auto &c: s) {
            int idx = c - 'a';
            if(!p->next[idx]) p->next[idx] = new Trie();
            p = p->next[idx];
        }
        p->isWord = true;
    }
    
    void addWord(string word) {
        insert(word);
    }
    
    bool dfs(Trie *p, string word, int idx) {
        if(idx == word.size()-1) {
            if(word[idx] == '.') {
                for(int i=0;i<26;++i) {
                    if(p->next[i] != NULL && p->next[i]->isWord)  return true;
                }
                return false;
            }
            else {
                int nidx = word[idx] - 'a';
                if(p->next[nidx] == NULL) return false;
                else return p->next[nidx]->isWord;
            }
        }
        
        if(word[idx] == '.') {
            for(int i=0;i<26;++i) {
                if(p->next[i] != NULL && dfs(p->next[i], word, idx+1)) return true;
            }
        }
        else {
            int nidx = word[idx] - 'a';
            if(! p->next[nidx]) return false;
            if(p->next[nidx] && dfs(p->next[nidx], word, idx+1)) return true;
        }
        return false;
    }
    
    // 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) {
        bool flag = false;
        for(int i=0;i<26;++i) {
            if(root->next[i] != NULL) {
                flag = true; break;
            }
        }
        if(!flag) return false;
        
        return dfs(root, word, 0);
    }
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
View Code

 

posted @ 2015-11-17 19:36  流白  阅读(227)  评论(0编辑  收藏  举报