/** * Initialize your data structure here. */ publicWordDictionary() { root = newNode(); }
/** * Adds a word into the data structure. */ publicvoidaddWord(String word) { if (word == null || word.isEmpty()) return; Map<Character, Node> children = root.children; for (inti=0; i < word.length(); i++) { charc= word.charAt(i); Nodenode= children.getOrDefault(c, newNode()); node.val = c; children.put(c, node); children = node.children; if (i == word.length() - 1) node.isLeaf = 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) { return word == null || word.isEmpty() || helper(0, word, root); }
privatebooleanhelper(int start, String word, Node node) { if (start == word.length()) return node.isLeaf; charc= word.charAt(start); booleanresult=false; if (c == '.') { for (Map.Entry<Character, Node> entry : node.children.entrySet()) { result = helper(start + 1, word, entry.getValue()); if (result) break; } } else { if (node.children.containsKey(c)) { result = helper(start + 1, word, node.children.get(c)); } } return result; }
privatestaticclassNode { char val; booleanisLeaf=false; Map<Character, Node> children = newHashMap<>();