Skip to content

Commit

Permalink
[WEEK6](gmlwls96) Design Add and Search Words Data Structure
Browse files Browse the repository at this point in the history
  • Loading branch information
gmlwls96 committed Jan 14, 2025
1 parent 871575e commit 2826f54
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions design-add-and-search-words-data-structure/gmlwls96.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Node() {
val map = mutableMapOf<Char, Node?>()
var isEnd = false
}

class WordDictionary() {

val rootNode = Node()

// 시간 : O(n), 공간 : O(n)
fun addWord(word: String) {
var currentNode = rootNode
for (i in word.indices) {
val char = word[i]
if (currentNode.map[char] == null) {
currentNode.map[char] = Node()
}
currentNode = currentNode.map[char]!!
}
currentNode.isEnd = true
}

// 시간 : O(26*n), 공간: O(n)
fun search(word: String): Boolean {
return dfs(
pos = 0,
word = word,
node = rootNode
)
}

fun dfs(pos: Int, word: String, node: Node): Boolean {
var result = false
val char = word[pos]
val isLast = word.lastIndex == pos
node.map.forEach {
if (char == '.' || char == it.key) {
if (isLast) {
result = true
return@forEach
} else {
result = result or dfs(pos + 1, word, it.value!!)
}
}
}
return result
}
}

0 comments on commit 2826f54

Please sign in to comment.