211. Add and Search Word - Data structure design

用Trie, dp会TLE

 

 

class WordDictionary {
    class Trie{
        Trie[] children;
        boolean flag;
        Trie(){
            children = new Trie[26];
        }
    }

    /** Initialize your data structure here. */
    Trie root;
    public WordDictionary() {
         root = new Trie();
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        if(word.length() == 0) return;
        Trie newroot = root;
        for(char c : word.toCharArray()){
            if(newroot.children[c - 'a'] == null){
                Trie node = new Trie();
                newroot.children[c - 'a'] = node;
                newroot = node;
            }else{
                newroot = newroot.children[c - 'a'];
            }
        }
        newroot.flag = true;
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    public boolean search(String word) {
        if(word.length() == 0) return false;
        return match(root, 0, word);
    
    }
    
    public boolean match(Trie root, int start, String word){
        if(root == null) return false;
        if(start == word.length()) return root.flag;
        char c = word.charAt(start);
        if(c == '.'){
            for(int i = 0; i < 26; i++){
                if(match(root.children[i], start+1, word)) return true;
            }
        }else {
            return root.children[c - 'a'] != null && match(root.children[c - 'a'], start+1, word);
        }
        return false;
    }
}

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

 

posted @ 2018-10-22 13:36  jasoncool1  阅读(121)  评论(0编辑  收藏  举报