File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments