File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node () {
2
+ val map = mutableMapOf<Char , Node ?>()
3
+ var isEnd = false
4
+ }
5
+
6
+ class Trie () {
7
+ /* * insert, search, startWith 시간 복잡도 : O(n) * */
8
+ val rootNode = Node ()
9
+ fun insert (word : String ) {
10
+ var currentNode = rootNode
11
+ word.forEach { char ->
12
+ if (currentNode.map[char] == null ) {
13
+ currentNode.map[char] = Node ()
14
+ }
15
+ currentNode = currentNode.map[char]!!
16
+ }
17
+ currentNode.isEnd = true
18
+ }
19
+
20
+ fun search (word : String ): Boolean {
21
+ var currentNode = rootNode
22
+ word.forEach { char ->
23
+ if (currentNode.map[char] == null ) {
24
+ return false
25
+ } else {
26
+ currentNode = currentNode.map[char]!!
27
+ }
28
+ }
29
+ return currentNode.isEnd
30
+ }
31
+
32
+ fun startsWith (prefix : String ): Boolean {
33
+ var currentNode = rootNode
34
+ prefix.forEach { char ->
35
+ if (currentNode.map[char] == null ) {
36
+ return false
37
+ } else {
38
+ currentNode = currentNode.map[char]!!
39
+ }
40
+ }
41
+ return true
42
+ }
43
+ }
You can’t perform that action at this time.
0 commit comments