Skip to content

Commit 27a57ca

Browse files
committed
Add implement trie (prefix tree) solution
1 parent b71a31d commit 27a57ca

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 시간복잡도: O(L) (insert, search, startsWith 모두 동일)
3+
* 공간복잡도: O(ΣL × alphabetSize)
4+
*/
5+
6+
class Trie() {
7+
8+
private class Node {
9+
val child = arrayOfNulls<Node>(26)
10+
var isEnd: Boolean = false
11+
}
12+
13+
private val root = Node()
14+
15+
fun insert(word: String) {
16+
var cur = root
17+
for (ch in word) {
18+
val i = ch - 'a'
19+
if (cur.child[i] == null) {
20+
cur.child[i] = Node()
21+
}
22+
cur = cur.child[i]!!
23+
}
24+
cur.isEnd = true
25+
}
26+
27+
fun search(word: String): Boolean {
28+
val node = findNode(word)
29+
return node?.isEnd == true
30+
}
31+
32+
fun startsWith(prefix: String): Boolean {
33+
return findNode(prefix) != null
34+
}
35+
36+
private fun findNode(s: String): Node? {
37+
var cur = root
38+
for (ch in s) {
39+
val i = ch - 'a'
40+
val next = cur.child[i] ?: return null
41+
cur = next
42+
}
43+
return cur
44+
}
45+
}

0 commit comments

Comments
 (0)