|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import leetcode_study.Type.* |
| 5 | +import org.junit.jupiter.api.Test |
| 6 | + |
| 7 | +class `design-add-and-search-words-data-structure` { |
| 8 | + |
| 9 | + class Node { |
| 10 | + var isEnd: Boolean = false |
| 11 | + val next: MutableMap<Char, Node> = mutableMapOf() |
| 12 | + } |
| 13 | + |
| 14 | + class WordDictionary { |
| 15 | + private val root = Node() |
| 16 | + |
| 17 | + /** |
| 18 | + * TC: O(n), SC: O(n) |
| 19 | + */ |
| 20 | + fun addWord(word: String) { |
| 21 | + var now = root |
| 22 | + |
| 23 | + for (index in word.indices) { |
| 24 | + val node = |
| 25 | + if (now.next.containsKey(word[index])) { now.next[word[index]] } |
| 26 | + else Node().also { now.next[word[index]] = it } |
| 27 | + node?.let { now = it } |
| 28 | + } |
| 29 | + now.isEnd = true |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * TC: O(26^n), SC: O(n) |
| 34 | + */ |
| 35 | + fun search(word: String): Boolean { |
| 36 | + |
| 37 | + fun dfs(node: Node, word: String, index: Int): Boolean { |
| 38 | + return if (index == word.length) node.isEnd |
| 39 | + else if (word[index] == '.') { |
| 40 | + node.next.values.any { dfs(it, word, index + 1) } |
| 41 | + } |
| 42 | + else { |
| 43 | + node.next[word[index]]?.let { dfs(it, word, index + 1) } ?: false |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return dfs(this.root, word, 0) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + fun `문자열을 저장하고 검색하는 자료구조를 구현하라`() { |
| 53 | + inputCommands( |
| 54 | + Command(ADD, "bad"), |
| 55 | + Command(ADD, "dad"), |
| 56 | + Command(ADD, "mad"), |
| 57 | + Command(SEARCH, "pad", false), |
| 58 | + Command(SEARCH, "bad", true), |
| 59 | + Command(SEARCH, ".ad", true), |
| 60 | + Command(SEARCH, "b..", true), |
| 61 | + ) |
| 62 | + inputCommands( |
| 63 | + Command(ADD, "at"), |
| 64 | + Command(ADD, "and"), |
| 65 | + Command(ADD, "an"), |
| 66 | + Command(ADD, "add"), |
| 67 | + Command(SEARCH, "a", false), |
| 68 | + Command(SEARCH, ".at", false), |
| 69 | + Command(ADD, "bat"), |
| 70 | + Command(SEARCH,".at", true), |
| 71 | + Command(SEARCH,"an.", true), |
| 72 | + Command(SEARCH,"a.d.", false), |
| 73 | + Command(SEARCH,"b.", false), |
| 74 | + Command(SEARCH,"a.d", true), |
| 75 | + Command(SEARCH,".", false) |
| 76 | + ) |
| 77 | + } |
| 78 | + |
| 79 | + private fun inputCommands(vararg commands: Command) { |
| 80 | + val dictionary = WordDictionary() |
| 81 | + for (command in commands) { |
| 82 | + when(command.type) { |
| 83 | + ADD -> dictionary.addWord(command.word) |
| 84 | + SEARCH -> dictionary.search(command.word) shouldBe command.expect |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +data class Command( |
| 91 | + val type: Type, |
| 92 | + val word: String, |
| 93 | + val expect : Boolean? = null |
| 94 | +) |
| 95 | + |
| 96 | +enum class Type { |
| 97 | + ADD, SEARCH; |
| 98 | +} |
0 commit comments