1
1
import java .util .HashMap ;
2
2
import java .util .Map ;
3
3
4
- // Map으로 풀려버려서 당황..
5
- // 이진트리? 어떤식으로 풀어야 할지 자료구조 정하고 다시 풀어보기..
4
+ // 한 글자씩 잘라서 하위 자식 노드들로 관리
5
+ // search 동작은 기존 그대로 Map자료구조에서 찾고, 이후 prefix연산에서 속도를 개선 (230ms -> 30ms)
6
6
class Trie {
7
7
8
- Map <String , Boolean > tMap ;
8
+ private Trie [] child ;
9
+ private Character val ;
10
+ private Map <String , Boolean > cMap ;
9
11
10
12
public Trie () {
11
- this .tMap = new HashMap <>();
13
+ this .cMap = new HashMap <>();
14
+ this .val = null ;
12
15
}
13
16
14
17
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 ));
16
40
}
17
41
18
42
public boolean search (String word ) {
19
- return this .tMap .containsKey (word );
43
+ return this .cMap .containsKey (word );
20
44
}
45
+
46
+ // public boolean search(String word) {
47
+
48
+ // }
21
49
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 ;
25
53
}
26
54
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 ));
28
61
}
29
62
}
30
63
@@ -35,3 +68,32 @@ public boolean startsWith(String prefix) {
35
68
* boolean param_2 = obj.search(word);
36
69
* boolean param_3 = obj.startsWith(prefix);
37
70
*/
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