|
| 1 | +/** |
| 2 | + 연결 리스트를 통해, 트리 구조를 만들고 탐색하는 방식 |
| 3 | +*/ |
| 4 | +class Trie { |
| 5 | + public Map<Character, WordNode> wordMap; |
| 6 | + |
| 7 | + public Trie() { |
| 8 | + wordMap = new HashMap<>(); |
| 9 | + } |
| 10 | + |
| 11 | + public void insert(String word) { |
| 12 | + WordNode wordNode = null; |
| 13 | + char ch = word.charAt(0); |
| 14 | + wordNode = wordMap.get(ch); |
| 15 | + |
| 16 | + if(wordNode == null) { |
| 17 | + boolean isFirstWord = word.length() == 1; |
| 18 | + wordNode = new WordNode(ch, isFirstWord); |
| 19 | + wordMap.put(ch, wordNode); |
| 20 | + } |
| 21 | + |
| 22 | + for(int idx = 1; idx < word.length(); idx++) { |
| 23 | + char target = word.charAt(idx); |
| 24 | + boolean isLeaf = word.length() - 1 == idx; |
| 25 | + wordNode = wordNode.next.computeIfAbsent(target, key -> new WordNode(key, isLeaf)); |
| 26 | + } |
| 27 | + wordNode.isLeaf = true; |
| 28 | + } |
| 29 | + |
| 30 | + public boolean search(String word) { |
| 31 | + |
| 32 | + WordNode wordNode = null; |
| 33 | + char ch = word.charAt(0); |
| 34 | + wordNode = wordMap.get(ch); |
| 35 | + if (wordNode == null) return false; |
| 36 | + |
| 37 | + |
| 38 | + for(int idx = 1; idx < word.length(); idx++) { |
| 39 | + char target = word.charAt(idx); |
| 40 | + if (!wordNode.next.containsKey(target)) { |
| 41 | + return false; |
| 42 | + } |
| 43 | + wordNode = wordNode.next.get(target); |
| 44 | + } |
| 45 | + |
| 46 | + return wordNode.isLeaf; |
| 47 | + } |
| 48 | + |
| 49 | + public boolean startsWith(String word) { |
| 50 | + |
| 51 | + WordNode wordNode = null; |
| 52 | + char ch = word.charAt(0); |
| 53 | + wordNode = wordMap.get(ch); |
| 54 | + if (wordNode == null) return false; |
| 55 | + |
| 56 | + |
| 57 | + for(int idx = 1; idx < word.length(); idx++) { |
| 58 | + char target = word.charAt(idx); |
| 59 | + if (!wordNode.next.containsKey(target)) { |
| 60 | + return false; |
| 61 | + } |
| 62 | + wordNode = wordNode.next.get(target); |
| 63 | + } |
| 64 | + |
| 65 | + return true; |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +class WordNode { |
| 70 | + char ch; |
| 71 | + Map<Character, WordNode> next; |
| 72 | + boolean isLeaf; |
| 73 | + |
| 74 | + public WordNode(char ch) { |
| 75 | + this(ch, false); |
| 76 | + } |
| 77 | + |
| 78 | + public WordNode(char ch, boolean isLeaf) { |
| 79 | + next = new HashMap<>(); |
| 80 | + this.ch = ch; |
| 81 | + this.isLeaf = isLeaf; |
| 82 | + } |
| 83 | + |
| 84 | +} |
| 85 | + |
| 86 | +/** |
| 87 | + * Your Trie object will be instantiated and called as such: |
| 88 | + * Trie obj = new Trie(); |
| 89 | + * obj.insert(word); |
| 90 | + * boolean param_2 = obj.search(word); |
| 91 | + * boolean param_3 = obj.startsWith(prefix); |
| 92 | + */ |
0 commit comments