|
| 1 | +class WordDictionary { |
| 2 | + |
| 3 | + private final TrieNode root; |
| 4 | + |
| 5 | + public WordDictionary() { |
| 6 | + this.root = new TrieNode(); |
| 7 | + } |
| 8 | + |
| 9 | + public void addWord(String word) { |
| 10 | + TrieNode curr = root; |
| 11 | + for (char c : word.toCharArray()) { |
| 12 | + if (!curr.children.containsKey(c)) { |
| 13 | + curr.children.put(c, new TrieNode()); |
| 14 | + } |
| 15 | + curr = curr.children.get(c); |
| 16 | + } |
| 17 | + curr.isWord = true; |
| 18 | + } |
| 19 | + |
| 20 | + public boolean search(String word) { |
| 21 | + return searchHelper(word, 0, root); |
| 22 | + } |
| 23 | + |
| 24 | + private boolean searchHelper(String word, int idx, TrieNode curr) { |
| 25 | + if (idx == word.length()) { |
| 26 | + return curr.isWord; |
| 27 | + } |
| 28 | + if (curr.children.containsKey(word.charAt(idx))) { |
| 29 | + return searchHelper(word, idx + 1, curr.children.get(word.charAt(idx))); |
| 30 | + } |
| 31 | + if (word.charAt(idx) == '.') { |
| 32 | + for (char c : curr.children.keySet()) { |
| 33 | + if (searchHelper(word, idx + 1, curr.children.get(c))) { |
| 34 | + return true; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | + private static class TrieNode { |
| 43 | + |
| 44 | + private final Map<Character, TrieNode> children; |
| 45 | + private boolean isWord; |
| 46 | + |
| 47 | + public TrieNode() { |
| 48 | + this.children = new HashMap<>(); |
| 49 | + this.isWord = false; |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Your WordDictionary object will be instantiated and called as such: |
| 56 | + * WordDictionary obj = new WordDictionary(); |
| 57 | + * obj.addWord(word); |
| 58 | + * boolean param_2 = obj.search(word); |
| 59 | + */ |
0 commit comments