|
| 1 | +class WordDictionary { |
| 2 | + |
| 3 | + private class TrieNode { |
| 4 | + Map<Character, TrieNode> children = new HashMap<>(); |
| 5 | + boolean isEndOfWord = false; |
| 6 | + } |
| 7 | + |
| 8 | + private TrieNode root; |
| 9 | + |
| 10 | + public WordDictionary() { |
| 11 | + root = new TrieNode(); |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * 시간 복잡도: O(n), n = 단어의 길이 |
| 16 | + * 공간 복잡도: O(n) |
| 17 | + */ |
| 18 | + public void addWord(String word) { |
| 19 | + TrieNode node = root; |
| 20 | + |
| 21 | + for (int i = 0; i < word.length(); i++) { |
| 22 | + char c = word.charAt(i); |
| 23 | + node.children.putIfAbsent(c, new TrieNode()); |
| 24 | + node = node.children.get(c); |
| 25 | + } |
| 26 | + node.isEndOfWord = true; |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * 시간 복잡도: O(26^n), n = 단어의 길이 |
| 31 | + * 공간 복잡도: O(n) |
| 32 | + */ |
| 33 | + public boolean search(String word) { |
| 34 | + return searchInNode(word, 0, root); |
| 35 | + } |
| 36 | + |
| 37 | + private boolean searchInNode(String word, int index, TrieNode node) { |
| 38 | + if (index == word.length()) { |
| 39 | + return node.isEndOfWord; |
| 40 | + } |
| 41 | + |
| 42 | + char c = word.charAt(index); |
| 43 | + if (c != '.') { |
| 44 | + if (node.children.containsKey(c)) { |
| 45 | + return searchInNode(word, index + 1, node.children.get(c)); |
| 46 | + } else { |
| 47 | + return false; |
| 48 | + } |
| 49 | + } else { |
| 50 | + for (TrieNode childNode : node.children.values()) { |
| 51 | + if (searchInNode(word, index + 1, childNode)) { |
| 52 | + return true; |
| 53 | + } |
| 54 | + } |
| 55 | + return false; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments