Skip to content

Commit

Permalink
Add a solution to the problem on Kotlin (#269)
Browse files Browse the repository at this point in the history
* Solution. Longest Common Subsequence
  • Loading branch information
MAGistR-bit authored Mar 22, 2024
1 parent cf6b035 commit 7d16656
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions 11_dynamic_programming/kotlin/LongestCommonSubsequence.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import kotlin.math.max

fun main() {
val wordA = "hish"
val wordB = "fish"
getLongestCommonSubSequence(wordA, wordB)
}

private fun getLongestCommonSubSequence(wordA: String, wordB: String) {
val cell = Array(wordA.length) { IntArray(wordB.length) }
for (i in wordA.indices) {
for (j in wordB.indices) {
// Буквы совпадают
if (wordA[i] == wordB[j]) {
if (i > 0 && j > 0) {
cell[i][j] = cell[i - 1][j - 1] + 1
} else {
cell[i][j] = 1
}
} else {
// Буквы не совпадают
if (i > 0 && j > 0) {
cell[i][j] = max(cell[i - 1][j], cell[i][j - 1])
} else {
cell[i][j] = 0
}
}
}
}
printResult(cell)
}

fun printResult(array: Array<IntArray>) {
for (row in array) {
println(row.contentToString())
}
}

0 comments on commit 7d16656

Please sign in to comment.