|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +class WordDictionary { |
| 5 | + // ์๊ฐ๋ณต์ก๋: O(N), N(word์ ๊ธธ์ด) |
| 6 | + // ๊ณต๊ฐ๋ณต์ก๋: O(N) |
| 7 | + Map<Character, WordDictionary> child; |
| 8 | + boolean isEnd; |
| 9 | + |
| 10 | + public WordDictionary() { |
| 11 | + child = new HashMap<>(); |
| 12 | + isEnd = false; |
| 13 | + } |
| 14 | + |
| 15 | + public void addWord(String word) { |
| 16 | + var node = this; |
| 17 | + for (int i = 0; i < word.length(); i++) { |
| 18 | + char c = word.charAt(i); |
| 19 | + |
| 20 | + node.child.putIfAbsent(c, new WordDictionary()); |
| 21 | + node = node.child.get(c); |
| 22 | + |
| 23 | + if (i == word.length() - 1) { |
| 24 | + node.isEnd = true; |
| 25 | + return; |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public boolean search(String word) { |
| 31 | + return searchHelper(word, 0, this); |
| 32 | + } |
| 33 | + |
| 34 | + private boolean searchHelper(String word, int index, WordDictionary node) { |
| 35 | + if (index == word.length()) { |
| 36 | + return node.isEnd; |
| 37 | + } |
| 38 | + |
| 39 | + char c = word.charAt(index); |
| 40 | + // . ์ด ๋์ค๋ฉด ํด๋น ๋
ธ๋์ ์์ ๋
ธ๋๋ค์ ๋ํด ๋ชจ๋ ์ฌ๊ท๋ฅผ ๋๋ฆฐ๋ค |
| 41 | + if (c == '.') { |
| 42 | + for (WordDictionary childNode : node.child.values()) { |
| 43 | + if (searchHelper(word, index + 1, childNode)) { |
| 44 | + return true; |
| 45 | + } |
| 46 | + } |
| 47 | + return false; |
| 48 | + } else { |
| 49 | + var childNode = node.child.get(c); |
| 50 | + if (childNode == null) { |
| 51 | + return false; |
| 52 | + } |
| 53 | + return searchHelper(word, index + 1, childNode); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Your WordDictionary object will be instantiated and called as such: |
| 60 | + * WordDictionary obj = new WordDictionary(); |
| 61 | + * obj.addWord(word); |
| 62 | + * boolean param_2 = obj.search(word); |
| 63 | + */ |
0 commit comments