-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCodeQ1143Tabulation.java
More file actions
50 lines (48 loc) · 1.66 KB
/
leetCodeQ1143Tabulation.java
File metadata and controls
50 lines (48 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package DynamicProgramming ;
public class leetCodeQ1143Tabulation {
// Tabulation
public static int longestCommonSubsequence(String a, String b) {
int m = a.length(), n = b.length();
// i = m-1 to 0 | j = n-1 to 0
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (a.charAt(i - 1) == b.charAt(j - 1)) {
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
return dp[m][n];
}
// Space Oprimization
public static int longestCommonSubsequenceSO(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[2][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
dp[1][j] = 0;
else if (a.charAt(i - 1) == b.charAt(j - 1)) {
dp[1][j] = 1 + dp[0][j - 1];
} else {
dp[1][j] = Math.max(dp[1][j - 1], dp[0][j]);
}
}
// Copy paste
for (int j = 0; j <= n; j++) {
dp[0][j] = dp[1][j];
}
}
return dp[1][n];
}
public static void main(String[] args) {
String a = "abcde" ;
String b = "ace" ;
System.out.println(longestCommonSubsequence(a, b));
System.out.println(longestCommonSubsequenceSO(a, b));
}
}