1 public class WordDictionary {
 2     public class TrieNode {
 3         TrieNode[] children = new TrieNode[26];
 4         boolean isWord;
 5         TrieNode(){}
 6     }
 7     
 8     private TrieNode root;
 9     
10     public WordDictionary() {
11         root = new TrieNode();
12     }
13     // Adds a word into the data structure.
14     public void addWord(String word) {
15         TrieNode current = root;
16         for (int i = 0; i < word.length(); i++) {
17             if (current.children[word.charAt(i) - 'a'] == null) {
18                 current.children[word.charAt(i) - 'a'] = new TrieNode();
19             }
20             current = current.children[word.charAt(i) - 'a'];
21         }
22         current.isWord = true;
23     }
24 
25     // Returns if the word is in the data structure. A word could
26     // contain the dot character '.' to represent any one letter.
27     public boolean search(String word) {
28         TrieNode current = root;
29         return search(word.toCharArray(), 0, root);
30     }
31     
32     private boolean search(char[] letters, int index, TrieNode root) {
33         if (index == letters.length) {
34             return root.isWord;
35         }
36         if (letters[index] != '.') {
37             return root.children[letters[index] - 'a'] != null && search(letters, index + 1, root.children[letters[index] - 'a']);
38         } else {
39             for (int i = 0; i < 26; i++) {
40                 if (root.children[i] != null && search(letters, index + 1, root.children[i])) {
41                     return true;
42                 }
43             }
44         }
45         return false;
46     }
47 }
48 
49 // Your WordDictionary object will be instantiated and called as such:
50 // WordDictionary wordDictionary = new WordDictionary();
51 // wordDictionary.addWord("word");
52 // wordDictionary.search("pattern");

1. check children is null or not.

posted on 2016-06-30 06:50  keepshuatishuati  阅读(136)  评论(0编辑  收藏  举报