Note:
You may assume that all words are consist of lowercase lettersa-z.
2. Implementation
(1) Trie + Backtracking
classWordDictionary {classTrieNode {char val;boolean isWord;TrieNode[] childNode;publicTrieNode(char val) {this.val= val; childNode =newTrieNode[26]; } }TrieNode root; /** Initialize your data structure here. */publicWordDictionary() { root =newTrieNode(' '); } /** Adds a word into the data structure. */publicvoidaddWord(String word) {if (word ==null||word.length() ==0) {return; }TrieNode curNode = root;for (char c :word.toCharArray()) {int index = c -'a';if (curNode.childNode[index] ==null) {curNode.childNode[index] =newTrieNode(c); } curNode =curNode.childNode[index]; }curNode.isWord=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) {if (word ==null||word.length() ==0) {returnfalse; }returnsearchByDFS(root,0, word); }publicbooleansearchByDFS(TrieNode node,int depth,String word) {if (depth ==word.length()) {returnnode.isWord; }char c =word.charAt(depth);if (c =='.') {for (TrieNode childNode :node.childNode) {if (childNode !=null&&searchByDFS(childNode, depth +1, word)) {returntrue; } }returnfalse; }else {int index = c -'a';returnnode.childNode[index] !=null&&searchByDFS(node.childNode[index], depth +1, word); } }}/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * boolean param_2 = obj.search(word); */