File tree 1 file changed +7
-6
lines changed
scripts/algorithms/I/Implement Trie (Prefix Tree)
1 file changed +7
-6
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 67 ms (Top 53.89%) | Memory: 70 MB (Top 22.15%)
1
2
class Trie {
2
3
private class Node {
3
4
char character ;
@@ -13,31 +14,31 @@ public Trie() {
13
14
root = new Node ('\0' );
14
15
map = new HashMap <>();
15
16
}
16
-
17
+
17
18
public void insert (String word ) {
18
19
Node temp = root ;
19
20
for (char c : word .toCharArray ()){
20
21
int index = c -'a' ;
21
22
if (temp .sub [index ] == null )
22
23
temp .sub [index ] = new Node (c );
23
-
24
+
24
25
temp = temp .sub [index ];
25
26
}
26
27
map .put (word , true );
27
28
}
28
-
29
+
29
30
public boolean search (String word ) {
30
31
return map .containsKey (word );
31
32
}
32
-
33
+
33
34
public boolean startsWith (String prefix ) {
34
35
Node temp = root ;
35
36
for (char c : prefix .toCharArray ()){
36
37
int index = c -'a' ;
37
38
if (temp .sub [index ] == null )
38
39
return false ;
39
- temp = temp .sub [index ];
40
+ temp = temp .sub [index ];
40
41
}
41
42
return true ;
42
43
}
43
- }
44
+ }
You can’t perform that action at this time.
0 commit comments