Skip to content

Commit f52d358

Browse files
committed
Add Longest Common Subsequence
1 parent 7fbd48f commit f52d358

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
fun longestCommonSubsequence(s1: String, s2: String): Int {
2+
// Base case: Set the last row and last column to 0 by
3+
// initializing the entire DP table with 0s.
4+
val dp = Array(s1.length + 1) { IntArray(s2.length + 1) }
5+
// Populate the DP table.
6+
for (i in s1.length - 1 downTo 0) {
7+
for (j in s2.length - 1 downTo 0) {
8+
// If the characters match, the length of the LCS at
9+
// 'dp[i][j]' is 1 + the LCS length of the remaining
10+
// substrings.
11+
if (s1[i] == s2[j]) {
12+
dp[i][j] = 1 + dp[i + 1][j + 1]
13+
} else {
14+
// If the characters don't match, the LCS length at
15+
// 'dp[i][j]' can be found by either:
16+
// 1. Excluding the current character of s1.
17+
// 2. Excluding the current character of s2.
18+
dp[i][j] = maxOf(dp[i + 1][j], dp[i][j + 1])
19+
}
20+
}
21+
}
22+
return dp[0][0]
23+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
fun longestCommonSubsequenceOptimized(s1: String, s2: String): Int {
2+
// Initialize 'prevRow' as the DP values of the last row.
3+
var prevRow = IntArray(s2.length + 1)
4+
for (i in s1.length - 1 downTo 0) {
5+
// Set the last cell of 'currRow' to 0 to set the base case for
6+
// this row. This is done by initializing the entire row to 0.
7+
val currRow = IntArray(s2.length + 1)
8+
for (j in s2.length - 1 downTo 0) {
9+
// If the characters match, the length of the LCS at
10+
// 'currRow[j]' is 1 + the LCS length of the remaining
11+
// substrings ('prevRow[j + 1]').
12+
if (s1[i] == s2[j]) {
13+
currRow[j] = 1 + prevRow[j + 1]
14+
} else {
15+
// If the characters don't match, the LCS length at
16+
// 'currRow[j]' can be found by either:
17+
// 1. Excluding the current character of s1 ('prevRow[j]').
18+
// 2. Excluding the current character of s2 ('currRow[j + 1]').
19+
currRow[j] = maxOf(prevRow[j], currRow[j + 1])
20+
}
21+
}
22+
// Update 'prevRow' with 'currRow' values for the next iteration.
23+
prevRow = currRow
24+
}
25+
return prevRow[0]
26+
}

0 commit comments

Comments
 (0)