-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1092. Shortest Common Supersequence
51 lines (51 loc) · 1.47 KB
/
1092. Shortest Common Supersequence
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
class Solution {
public void helper(String s1, String s2, int[][] dp) {
int n = s1.length();
int m = s2.length();
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
if(s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
}
public String shortestCommonSupersequence(String str1, String str2) {
int[][] dp = new int[str1.length() + 1][str2.length() + 1];
helper(str1, str2, dp);
int i = str1.length();
int j = str2.length();
String ans = "";
while (i > 0 && j > 0) {
if(str1.charAt(i - 1) == str2.charAt(j - 1)) {
ans += str1.charAt(i - 1);
i--;
j--;
}
else if(dp[i - 1][j] > dp[i][j - 1]) {
ans += str1.charAt(i - 1);
i--;
}
else {
ans += str2.charAt(j - 1);
j--;
}
}
while (i > 0) {
ans += str1.charAt(i - 1);
i--;
}
while (j > 0) {
ans += str2.charAt(j - 1);
j--;
}
String ans1 = "";
for(int k = ans.length() - 1; k >= 0; k--) {
ans1 += ans.charAt(k);
}
return ans1;
}
}