Skip to content

Commit 5249572

Browse files
committed
add: LongestCommonSubsequenceOptimized
1 parent 807f2b5 commit 5249572

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
public class LongestCommonSubsequenceOptimized {
2+
public int longestCommonSubsequenceOptimized(String s1, String s2) {
3+
// Initialize 'prevRow' as the DP values of the last row.
4+
int[] prevRow = new int[s2.length() + 1];
5+
for (int i = s1.length() - 1; i >= 0; i--) {
6+
// Set the last cell of 'currRow' to 0 to set the base case for
7+
// this row. This is done by initializing the entire row to 0.
8+
int[] currRow = new int[s2.length() + 1];
9+
for (int j = s2.length() - 1; j >= 0; j--) {
10+
// If the characters match, the length of the LCS at
11+
// 'currRow[j]' is 1 + the LCS length of the remaining
12+
// substrings ('prevRow[j + 1]').
13+
if (s1.charAt(i) == s2.charAt(j)) {
14+
currRow[j] = 1 + prevRow[j + 1];
15+
}
16+
// If the characters don't match, the LCS length at
17+
// 'currRow[j]' can be found by either:
18+
// 1. Excluding the current character of s1 ('prevRow[j]').
19+
// 2. Excluding the current character of s2 ('currRow[j + 1]').
20+
else {
21+
currRow[j] = Math.max(prevRow[j], currRow[j + 1]);
22+
}
23+
}
24+
// Update 'prevRow' with 'currRow' values for the next
25+
// iteration.
26+
prevRow = currRow;
27+
}
28+
return prevRow[0];
29+
}
30+
}

0 commit comments

Comments
 (0)