-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCodeQ1312ProperTabulation.java
More file actions
60 lines (56 loc) · 1.91 KB
/
leetCodeQ1312ProperTabulation.java
File metadata and controls
60 lines (56 loc) · 1.91 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
51
52
53
54
55
56
57
58
59
60
package DynamicProgramming;
public class leetCodeQ1312ProperTabulation {
// Proper 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];
}
// Proper Tabulation with Space Optimization .
public static int longestCommonSubsequence1(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 String reverse(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
s = sb.toString();
return s;
}
public static void main(String[] args) {
String s = "mbadm" ;
int lcs = longestCommonSubsequence(s, reverse(s));
int n = s.length();
System.out.println(n - lcs);
lcs = longestCommonSubsequence1(s, reverse(s)) ;
System.out.println(n-lcs);
}
}