File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments