Skip to content

Instantly share code, notes, and snippets.

@munguial
Created April 27, 2020 00:07
Show Gist options
  • Save munguial/caa3eb73583bf31be82b9b6e3af28e38 to your computer and use it in GitHub Desktop.
Save munguial/caa3eb73583bf31be82b9b6e3af28e38 to your computer and use it in GitHub Desktop.
Day 26 - Longest Common Subsequence
// https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/531/week-4/3311/
class Solution {
fun longestCommonSubsequence(text1: String, text2: String): Int {
val dp = Array(text1.length + 1, {IntArray(text2.length + 1)})
for (i in 1..text1.length) {
for (j in 1..text2.length) {
dp[i][j] = when {
text1.get(i - 1) == text2.get(j - 1) -> dp[i - 1][j - 1] + 1
else -> maxOf(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[text1.length][text2.length]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment