class WordDictionary {
    class TrieNode {
        public TrieNode[] children = new TrieNode[26];
        public boolean isEnd;
    }
    
    private TrieNode root;

    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new TrieNode();
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode runner = root;
        for (char c : word.toCharArray()) {
            if (runner.children[(int)(c - 'a')] == null) {
                runner.children[(int)(c - 'a')] = new TrieNode();
            }
            runner = runner.children[(int)(c - 'a')];
        }
        runner.isEnd = 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) {
        return search(word.toCharArray(), 0, root);
    }
    
    private boolean search(char[] word, int index, TrieNode current) {
        if (index == word.length) {
            return current.isEnd;
        }
        
        if (word[index] != '.') {
            return current.children[(int)(word[index] - 'a')] != null && search(word, index + 1, current.children[(int)(word[index] - 'a')]);
        } else {
            boolean found = false;
            for (int i = 0; i < 26; i++) {
                if (current.children[i] != null && search(word, index + 1, current.children[i])) {
                    return true;
                }
            }
        }
        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);
 */

 

1. When dot happened, each path should be scanned.

2. Each node will not contain any current char info.

posted on 2017-08-21 12:44  keepshuatishuati  阅读(110)  评论(0编辑  收藏  举报