参考
Longest common subsequence
然后回溯dp[][] matrix
public String shortestCommonSupersequence(String str1, String str2) {
int m = str1.length();
int n = str2.length();
char[] char1 = str1.toCharArray();
char[] char2 = str2.toCharArray();
int[][] dp = LCS(str1, str2);
StringBuilder sb = new StringBuilder();
int i = m, j = n;
while (i > 0 || j > 0) {
char ch = ' ';
if (i == 0) {
ch = char2[j - 1];
j--;
} else if (j == 0) {
ch = char1[i - 1];
i--;
} else if (char1[i - 1] == char2[j - 1]) {
ch = char1[i - 1];
i--;
j--;
} else if (dp[i][j - 1] == dp[i][j]) {
ch = char2[j - 1];
j--;
} else if (dp[i - 1][j] == dp[i][j]) {
ch = char1[i - 1];
i--;
}
sb.append(ch);
}
return sb.reverse().toString();
}
private int[][] LCS(String str1, String str2) {
int m = str1.length(), n = str2.length();
int[][] dp = 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)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp;
}