與208.前綴樹的設計是一樣的,關鍵點在于word中存在通配符“.",所以針對該特殊情況,在search時針對這里進行全子節點的深度搜索
class WordDictionary {TrieNode root;private class TrieNode {char val;// 當前節點的值,冗余了,可不寫Map<Character, TrieNode> children;// 當前節點的孩子boolean isEnd;// 標記是否是葉節點,默認為falsepublic TrieNode() {children = new HashMap<>();}}public WordDictionary() {root = new TrieNode();}public void addWord(String word) {TrieNode cur = root;for (int i = 0; i < word.length(); i++) {//不存在該字符則在子節點中創建if (!cur.children.containsKey(word.charAt(i))) {cur.children.put(word.charAt(i), new TrieNode());}//指針向子節點偏移cur = cur.children.get(word.charAt(i));}cur.isEnd = true;//創建到最后一個字符時就是葉節點,置為true}public boolean search(String word) {return search(word, root);}private boolean search(String word, TrieNode root) {TrieNode cur = root;for (int i = 0; i < word.length(); i++) {//1.如果word中當前位置是.那么需要遍歷當前節點之后的每條路徑if (word.charAt(i) == '.') {Set<Character> children = cur.children.keySet();for (Character child : children) {if (search(word.substring(i + 1), cur.children.get(child))) {return true;}}return false;}//2.如果word中當前位置字符并不存在直接返回falseif (!cur.children.containsKey(word.charAt(i))) {return false;}//3.如果word中當前位置字符匹配,指針向子節點偏移cur = cur.children.get(word.charAt(i));}return cur.isEnd;}
}/*** Your WordDictionary object will be instantiated and called as such:* WordDictionary obj = new WordDictionary();* obj.addWord(word);* boolean param_2 = obj.search(word);*/