-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
34 lines (34 loc) · 1.16 KB
/
Solution.java
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
class Solution {
public String shortestCommonSupersequence(String str1, String str2) {
int m = str1.length(), n = str2.length();
int[][] f = new int[m + 1][n + 1];
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
f[i][j] = f[i - 1][j - 1] + 1;
} else {
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
}
}
}
int i = m, j = n;
StringBuilder ans = new StringBuilder();
while (i > 0 || j > 0) {
if (i == 0) {
ans.append(str2.charAt(--j));
} else if (j == 0) {
ans.append(str1.charAt(--i));
} else {
if (f[i][j] == f[i - 1][j]) {
ans.append(str1.charAt(--i));
} else if (f[i][j] == f[i][j - 1]) {
ans.append(str2.charAt(--j));
} else {
ans.append(str1.charAt(--i));
--j;
}
}
}
return ans.reverse().toString();
}
}