Skip to content

Commit 67b1117

Browse files
committed
Implement Trie (Prefix Tree)
1 parent 5b12185 commit 67b1117

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
Time Complexity (n = length of word/prefix)
3+
- initialization: O(1)
4+
- insert: O(n)
5+
- search: O(n)
6+
- startsWith: O(n)
7+
8+
Space Complexity: O(n * c) (c = calls)
9+
- 길이 3인 알파벳 소문자 문자열의 가짓수 : 26^3 = 17,576
10+
- 길이 4인 알파벳 소문자 문자열의 가짓수 : 26^4 = 456,976
11+
만약 n이 3 이하였다면, 3만 번의 call 동안 trie가 포화되어 공간 복잡도가 O(26 * n) = O(n) 이었을 것.
12+
하지만 n이 2,000으로 충분히 크기 때문에 trie가 포화되지는 않을 것이므로, 공간 복잡도는 O(n * c).
13+
*/
14+
class Trie {
15+
16+
class Node {
17+
public char val;
18+
public boolean ends;
19+
public HashMap<Character, Node> children;
20+
21+
Node() {
22+
this.children = new HashMap<>();
23+
}
24+
}
25+
26+
public Node root;
27+
28+
public Trie() {
29+
this.root = new Node();
30+
}
31+
32+
public void insert(String word) {
33+
Node curr = this.root;
34+
35+
for (char ch : word.toCharArray()) {
36+
curr = curr.children.computeIfAbsent(ch, c -> new Node());
37+
curr.val = ch;
38+
}
39+
curr.ends = true;
40+
}
41+
42+
public boolean search(String word) {
43+
Node curr = this.root;
44+
45+
for (char ch : word.toCharArray()) {
46+
curr = curr.children.get(ch);
47+
if (curr == null)
48+
return false;
49+
}
50+
return curr.ends;
51+
}
52+
53+
public boolean startsWith(String prefix) {
54+
Node curr = this.root;
55+
56+
for (char ch : prefix.toCharArray()) {
57+
curr = curr.children.get(ch);
58+
if (curr == null)
59+
return false;
60+
}
61+
return true;
62+
}
63+
}
64+
65+
/**
66+
* Your Trie object will be instantiated and called as such:
67+
* Trie obj = new Trie();
68+
* obj.insert(word);
69+
* boolean param_2 = obj.search(word);
70+
* boolean param_3 = obj.startsWith(prefix);
71+
*/

0 commit comments

Comments
 (0)