File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +48
-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 WordDictionary () {
7
+
8
+ val rootNode = Node ()
9
+
10
+ // 시간 : O(n), 공간 : O(n)
11
+ fun addWord (word : String ) {
12
+ var currentNode = rootNode
13
+ for (i in word.indices) {
14
+ val char = word[i]
15
+ if (currentNode.map[char] == null ) {
16
+ currentNode.map[char] = Node ()
17
+ }
18
+ currentNode = currentNode.map[char]!!
19
+ }
20
+ currentNode.isEnd = true
21
+ }
22
+
23
+ // 시간 : O(26*n), 공간: O(n)
24
+ fun search (word : String ): Boolean {
25
+ return dfs(
26
+ pos = 0 ,
27
+ word = word,
28
+ node = rootNode
29
+ )
30
+ }
31
+
32
+ fun dfs (pos : Int , word : String , node : Node ): Boolean {
33
+ var result = false
34
+ val char = word[pos]
35
+ val isLast = word.lastIndex == pos
36
+ node.map.forEach {
37
+ if (char == ' .' || char == it.key) {
38
+ if (isLast) {
39
+ result = true
40
+ return @forEach
41
+ } else {
42
+ result = result or dfs(pos + 1 , word, it.value!! )
43
+ }
44
+ }
45
+ }
46
+ return result
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments