Skip to content

Commit 2826f54

Browse files
committed
[WEEK6](gmlwls96) Design Add and Search Words Data Structure
1 parent 871575e commit 2826f54

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

0 commit comments

Comments
 (0)