find 函数很重要,index 用来标记从什么地方开始搜索。搜索成功的退出条件是 index 等于 word 的长度。
classTrieNode {publicTrieNode[] children;publicboolean endWord;publicTrieNode() { children =newTrieNode[26]; endWord =false; }}publicclassWordDictionary {privateTrieNode root;publicWordDictionary() { root =newTrieNode(); }// Adds a word into the data structure.publicvoidaddWord(String word) {TrieNode curr = root;for (int i =0; i <word.length(); i++) {char c =word.charAt(i);if (curr.children[c -'a'] ==null) {curr.children[c -'a'] =newTrieNode(); } curr =curr.children[c -'a']; }curr.endWord=true; }// Returns if the word is in the data structure. A word could// contain the dot character '.' to represent any one letter.publicbooleansearch(String word) {returnfind(word,0, root); }publicbooleanfind(String word,int index,TrieNode curr) {if (index ==word.length()) {returncurr.endWord; }char c =word.charAt(index);if (c =='.') {for (int i =0; i <26; i++) {if (curr.children[i] !=null) {if (find(word, index +1,curr.children[i])) {returntrue; } } }returnfalse; } elseif (curr.children[c -'a'] !=null) {returnfind(word, index +1,curr.children[c -'a']); } else {returnfalse; } }}// Your WordDictionary object will be instantiated and called as such:// WordDictionary wordDictionary = new WordDictionary();// wordDictionary.addWord("word");// wordDictionary.search("pattern");