Note:
You may assume that all words are consist of lowercase lettersa-z.
这题用trie,然后search时一定要递归,试了好久都没试出非递归版本。
publicclassWordDictionary {privateTrieNode root; /** Initialize your data structure here. */publicWordDictionary() { root =newTrieNode(); } /** Adds a word into the data structure. */publicvoidaddWord(String word) {if (word ==null||word.isEmpty()) {return; }TrieNode last = root;for (int i =0; i <word.length(); i++) {TrieNode cur =last.children.get(word.charAt(i));if (cur ==null) { cur =newTrieNode();last.children.put(word.charAt(i), cur); } last = cur; }last.end=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) {returnsearch(word, root,0); }privatebooleansearch(String word,TrieNode node,int start) {if (start ==word.length()) {returnnode.end; }char c =word.charAt(start);if (c =='.') {for (TrieNode candidate :node.children.values()) {if (search(word, candidate, start +1)) {returntrue; } }returnfalse; } else {TrieNode next =node.children.get(c);if (next ==null) {returnfalse; } else {returnsearch(word, next, start +1); } } }classTrieNode {Map<Character,TrieNode> children =newHashMap<>();boolean end; }}/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * boolean param_2 = obj.search(word); */