From 2826f54500f22c8ee8125150fd7deebb4f030edc Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Tue, 14 Jan 2025 22:00:14 +0900 Subject: [PATCH] [WEEK6](gmlwls96) Design Add and Search Words Data Structure --- .../gmlwls96.kt | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 design-add-and-search-words-data-structure/gmlwls96.kt diff --git a/design-add-and-search-words-data-structure/gmlwls96.kt b/design-add-and-search-words-data-structure/gmlwls96.kt new file mode 100644 index 000000000..29c7a9ccc --- /dev/null +++ b/design-add-and-search-words-data-structure/gmlwls96.kt @@ -0,0 +1,48 @@ +class Node() { + val map = mutableMapOf() + 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 + } +}