Skip to content

Commit 51256af

Browse files
add: prefix tire 개선
1 parent 69c9e82 commit 51256af

File tree

1 file changed

+72
-10
lines changed

1 file changed

+72
-10
lines changed
Lines changed: 72 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,63 @@
11
import java.util.HashMap;
22
import java.util.Map;
33

4-
// Map으로 풀려버려서 당황..
5-
// 이진트리? 어떤식으로 풀어야 할지 자료구조 정하고 다시 풀어보기..
4+
// 한 글자씩 잘라서 하위 자식 노드들로 관리
5+
// search 동작은 기존 그대로 Map자료구조에서 찾고, 이후 prefix연산에서 속도를 개선 (230ms -> 30ms)
66
class Trie {
77

8-
Map<String, Boolean> tMap;
8+
private Trie[] child;
9+
private Character val;
10+
private Map<String, Boolean> cMap;
911

1012
public Trie() {
11-
this.tMap = new HashMap<>();
13+
this.cMap = new HashMap<>();
14+
this.val = null;
1215
}
1316

1417
public void insert(String word) {
15-
this.tMap.put(word, true);
18+
if(this.cMap.containsKey(word)) return;
19+
20+
this.cMap.put(word, true);
21+
this.innerInsert(word);
22+
}
23+
24+
public void innerInsert(String word) {
25+
if(word.length() == 0) return;
26+
27+
if(this.child == null) {
28+
this.child = new Trie[26];
29+
}
30+
31+
char c = word.charAt(0);
32+
int idx = c - 97;
33+
34+
if(this.child[idx] == null) {
35+
this.child[idx] = new Trie();
36+
this.child[idx].val = c;
37+
}
38+
39+
this.child[idx].innerInsert(word.substring(1));
1640
}
1741

1842
public boolean search(String word) {
19-
return this.tMap.containsKey(word);
43+
return this.cMap.containsKey(word);
2044
}
45+
46+
// public boolean search(String word) {
47+
48+
// }
2149

22-
public boolean startsWith(String prefix) {
23-
for(String key : this.tMap.keySet()) {
24-
if(key.startsWith(prefix)) return true;
50+
public boolean startsWith(String word) {
51+
if(word.length() == 0) {
52+
return true;
2553
}
2654

27-
return false;
55+
char c = word.charAt(0);
56+
int idx = c - 97;
57+
if(this.child == null || this.child[idx] == null || this.child[idx].val == null) return false;
58+
59+
60+
return this.child[idx].startsWith(word.substring(1));
2861
}
2962
}
3063

@@ -35,3 +68,32 @@ public boolean startsWith(String prefix) {
3568
* boolean param_2 = obj.search(word);
3669
* boolean param_3 = obj.startsWith(prefix);
3770
*/
71+
72+
73+
// Map으로 풀려버려서 당황..
74+
// 이진트리? 어떤식으로 풀어야 할지 자료구조 정하고 다시 풀어보기..
75+
class BeforeTrie {
76+
77+
Map<String, Boolean> tMap;
78+
79+
public BeforeTrie() {
80+
this.tMap = new HashMap<>();
81+
}
82+
83+
public void insert(String word) {
84+
this.tMap.put(word, true);
85+
}
86+
87+
public boolean search(String word) {
88+
return this.tMap.containsKey(word);
89+
}
90+
91+
public boolean startsWith(String prefix) {
92+
for(String key : this.tMap.keySet()) {
93+
if(key.startsWith(prefix)) return true;
94+
}
95+
96+
return false;
97+
}
98+
}
99+

0 commit comments

Comments
 (0)