kt: add «1092. Shortest Common Supersequence»

URL:	https://leetcode.com/problems/shortest-common-supersequence/
This commit is contained in:
Matej Focko 2025-02-28 08:58:44 +01:00
parent c1c49bfcfe
commit 49aed412b8
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,57 @@
class Solution {
fun shortestCommonSupersequence(
str1: String,
str2: String,
): String {
val (n, m) = str1.length to str2.length
val dp = Array(n + 1) { IntArray(m + 1) }
// Initialize base cases
(0..n).forEach { y -> dp[y][0] = y }
(0..m).forEach { x -> dp[0][x] = x }
// Precompute
(1..n).flatMap { y ->
(1..m).map { x -> x to y }
}.forEach { (x, y) ->
dp[y][x] =
when {
str1[y - 1] == str2[x - 1] -> dp[y - 1][x - 1] + 1
else -> 1 + listOf(dp[y - 1][x], dp[y][x - 1]).min()!!
}
}
val supersequence = StringBuilder()
var (x, y) = m to n
while (y > 0 && x > 0) {
when {
str1[y - 1] == str2[x - 1] -> {
supersequence.append(str1[y - 1])
y--
x--
}
dp[y - 1][x] < dp[y][x - 1] -> {
supersequence.append(str1[y - 1])
y--
}
else -> {
supersequence.append(str2[x - 1])
x--
}
}
}
while (y > 0) {
supersequence.append(str1[y - 1])
y--
}
while (x > 0) {
supersequence.append(str2[x - 1])
x--
}
return supersequence.reverse().toString()
}
}