|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +/** |
| 5 | + * WordDictionary |
| 6 | + * WordDictionary() - ๊ฐ์ฒด ์ด๊ธฐํ |
| 7 | + * void addWord(word) - ์๋ฃ ๊ตฌ์กฐ์ word ์ถ๊ฐ |
| 8 | + * boolean search(word) - ์๋ฃ ๊ตฌ์กฐ์ word ์์ผ๋ฉด true ์๋๋ฉด false ๋ฐํ |
| 9 | + - '.'๋ ์์ผ๋์นด๋๋ก ํ์ฉ ๊ฐ๋ฅ |
| 10 | + */ |
| 11 | +class WordDictionary { |
| 12 | + |
| 13 | + private Node root; |
| 14 | + |
| 15 | + public WordDictionary() { |
| 16 | + root = new Node(); |
| 17 | + } |
| 18 | + |
| 19 | + public void addWord(String word) { |
| 20 | + Node current = root; |
| 21 | + for (char c : word.toCharArray()) { |
| 22 | + if (!current.nodeCharacters.containsKey(c)) { |
| 23 | + current.nodeCharacters.put(c, new Node()); |
| 24 | + } |
| 25 | + current = current.nodeCharacters.get(c); |
| 26 | + } |
| 27 | + current.isEnd = true; |
| 28 | + } |
| 29 | + |
| 30 | + public boolean search(String word) { |
| 31 | + return searchInNode(word, 0, root); |
| 32 | + } |
| 33 | + |
| 34 | + private boolean searchInNode(String word, int idx, Node node) { |
| 35 | + |
| 36 | + if (node == null) { |
| 37 | + return false; |
| 38 | + } |
| 39 | + |
| 40 | + if (idx == word.length()) { |
| 41 | + return node.isEnd; |
| 42 | + } |
| 43 | + |
| 44 | + char c = word.charAt(idx); |
| 45 | + // ์์ผ๋์นด๋๋ Node์ ์๋ ์ ์ฒด ๊ฐ ๋ค ํ์ |
| 46 | + if (c == '.') { |
| 47 | + for (Node child : node.nodeCharacters.values()) { |
| 48 | + if (searchInNode(word, idx + 1, child)) { |
| 49 | + return true; |
| 50 | + } |
| 51 | + } |
| 52 | + return false; |
| 53 | + } else { |
| 54 | + Node current = node.nodeCharacters.get(c); |
| 55 | + return searchInNode(word, idx + 1, current); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + static class Node { |
| 60 | + |
| 61 | + boolean isEnd; |
| 62 | + |
| 63 | + Map<Character, Node> nodeCharacters; |
| 64 | + |
| 65 | + Node() { |
| 66 | + nodeCharacters = new HashMap<>(); |
| 67 | + isEnd = false; |
| 68 | + } |
| 69 | + |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +/** |
| 74 | + * Your WordDictionary object will be instantiated and called as such: |
| 75 | + * WordDictionary obj = new WordDictionary(); |
| 76 | + * obj.addWord(word); |
| 77 | + * boolean param_2 = obj.search(word); |
| 78 | + */ |
| 79 | + |
0 commit comments