|
| 1 | +/** |
| 2 | + * trie는 효율적으로 데이터를 저장하고 키를 통해 문자열 데이터 셋을 검색할 수 있는 트리 구조이다. |
| 3 | + * 해당 구조를 활용해 자동완성이나 스펠링 체크를 만들 수 있다. |
| 4 | + trie 클래스는 다음과 같이 구현할 수 있다. |
| 5 | + Trie() 클래스 생성자 |
| 6 | + void insert(String word) : trie로 문자열 word를 삽입 |
| 7 | + boolean search(String word) : 문자열 word가 trie에 있다면 true를 반환 |
| 8 | + boolean startsWith(String prefix) : prefix가 trie에 있다면 true를 반환 |
| 9 | + */ |
| 10 | +class Trie { |
| 11 | + |
| 12 | + private Node root; |
| 13 | + |
| 14 | + public Trie() { |
| 15 | + root = new Node(); |
| 16 | + } |
| 17 | + |
| 18 | + public void insert(String word) { |
| 19 | + Node current = root; |
| 20 | + for (char c : word.toCharArray()) { |
| 21 | + if (!current.getNodeCharacters().containsKey(c)) { |
| 22 | + current.getNodeCharacters().put(c, new Node()); |
| 23 | + } |
| 24 | + current = current.getNodeCharacters().get(c); |
| 25 | + } |
| 26 | + current.setEnd(); |
| 27 | + } |
| 28 | + |
| 29 | + public boolean search(String word) { |
| 30 | + Node current = root; |
| 31 | + for (char c : word.toCharArray()) { |
| 32 | + if (!current.getNodeCharacters().containsKey(c)) { |
| 33 | + return false; |
| 34 | + } |
| 35 | + current = current.getNodeCharacters().get(c); |
| 36 | + } |
| 37 | + return current.getEnd(); |
| 38 | + } |
| 39 | + |
| 40 | + public boolean startsWith(String prefix) { |
| 41 | + Node current = root; |
| 42 | + for (char c : prefix.toCharArray()) { |
| 43 | + if (!current.getNodeCharacters().containsKey(c)) { |
| 44 | + return false; |
| 45 | + } |
| 46 | + current = current.getNodeCharacters().get(c); |
| 47 | + } |
| 48 | + return true; |
| 49 | + } |
| 50 | + |
| 51 | + static class Node { |
| 52 | + |
| 53 | + // 문자열 끝 여부 |
| 54 | + private boolean isEnd; |
| 55 | + |
| 56 | + // 키 추출을 위한 맵 구조 |
| 57 | + private Map<Character, Node> nodeCharacters; |
| 58 | + |
| 59 | + Node() { |
| 60 | + nodeCharacters = new HashMap<>(); |
| 61 | + isEnd = false; |
| 62 | + } |
| 63 | + |
| 64 | + public boolean getEnd() { |
| 65 | + return this.isEnd; |
| 66 | + } |
| 67 | + |
| 68 | + public void setEnd() { |
| 69 | + this.isEnd = true; |
| 70 | + } |
| 71 | + |
| 72 | + public Map<Character, Node> getNodeCharacters() { |
| 73 | + return this.nodeCharacters; |
| 74 | + } |
| 75 | + |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +/** |
| 80 | + * Your Trie object will be instantiated and called as such: |
| 81 | + * Trie obj = new Trie(); |
| 82 | + * obj.insert(word); |
| 83 | + * boolean param_2 = obj.search(word); |
| 84 | + * boolean param_3 = obj.startsWith(prefix); |
| 85 | + */ |
| 86 | + |
0 commit comments