|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | +import kotlin.math.max |
| 6 | + |
| 7 | +class `longest-common-subsequence` { |
| 8 | + |
| 9 | + fun longestCommonSubsequence(text1: String, text2: String): Int { |
| 10 | + return usingDP(text1, text2) |
| 11 | + } |
| 12 | + |
| 13 | + /** |
| 14 | + * TC: O(2^(n + m)), SC: O(n + m) 시간초과!!! |
| 15 | + */ |
| 16 | + private fun usingBruteForce(text1: String, text2: String): Int { |
| 17 | + |
| 18 | + fun dfs(i: Int, j: Int): Int = |
| 19 | + if (i == text1.length || j == text2.length) 0 |
| 20 | + else if(text1[i] == text2[j]) 1 + dfs(i + 1, j + 1) |
| 21 | + else max(dfs(i + 1, j), dfs(i, j + 1)) |
| 22 | + |
| 23 | + return dfs(0, 0) |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * TC: O(n * m), SC: O(n * m) |
| 28 | + */ |
| 29 | + private fun usingMemoization(text1: String, text2: String): Int { |
| 30 | + |
| 31 | + fun dfs(i: Int, j: Int, memo: Array<IntArray>): Int { |
| 32 | + if (i == text1.length || j == text2.length) return 0 |
| 33 | + else if (memo[i][j] != -1) return memo[i][j] |
| 34 | + |
| 35 | + memo[i][j] = if(text1[i] == text2[j]) 1 + dfs(i + 1, j + 1, memo) |
| 36 | + else max(dfs(i + 1, j, memo), dfs(i, j + 1, memo)) |
| 37 | + |
| 38 | + return memo[i][j] |
| 39 | + } |
| 40 | + val memo = Array(text1.length) { IntArray(text2.length) { -1 } } |
| 41 | + return dfs(0, 0, memo) |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * TC: O(n * m), SC: O(n * m) |
| 46 | + */ |
| 47 | + private fun usingDP(text1: String, text2: String): Int { |
| 48 | + val dp = Array(text1.length + 1) { IntArray(text2.length + 1) } |
| 49 | + for (i in text1.indices) { |
| 50 | + for (j in text2.indices) { |
| 51 | + dp[i + 1][j + 1] = if (text1[i] == text2[j]) dp[i][j] + 1 |
| 52 | + else max(dp[i + 1][j], dp[i][j + 1]) |
| 53 | + } |
| 54 | + } |
| 55 | + return dp[text1.length][text2.length] |
| 56 | + } |
| 57 | + |
| 58 | + @Test |
| 59 | + fun `입력받은 두 문자열의 가장 긴 공통 부분 수열의 길이를 반환하라`() { |
| 60 | + longestCommonSubsequence("abcde", "ace") shouldBe 3 |
| 61 | + longestCommonSubsequence("abc", "abc") shouldBe 3 |
| 62 | + longestCommonSubsequence("abcdefghi", "defi") shouldBe 4 |
| 63 | + longestCommonSubsequence("abc", "def") shouldBe 0 |
| 64 | + } |
| 65 | +} |
0 commit comments