-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a solution to the problem on Kotlin (#269)
* Solution. Longest Common Subsequence
- Loading branch information
1 parent
cf6b035
commit 7d16656
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | ||
} | ||
} |