public String shortestCommonSupersequence(String str1, String str2) {
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
int m = arr1.length;
int n = arr2.length;
int k1 = maxOverlap(arr1, arr2);
int k2 = maxOverlap(arr2, arr1);
StringBuilder ans = new StringBuilder();
if (k1 > k2) {
ans.append(arr1);
for (int i = k1; i < n; i++) {
ans.append(arr2[i]);
}
}else{
ans.append(arr2);
for (int i = k2; i < m; i++) {
ans.append(arr1[i]);
}
}
return ans.toString();
}
public int maxOverlap(char[] arr1, char[] arr2) {
int m = arr1.length;
int n = arr2.length;
int[][] dp = new int[2][n + 1];
int ans = 0;
int INF = -0x3f3f3f3f;
int base = 0;
Arrays.fill(dp[base], INF);
dp[base][0] = 0;
base ^= 1;
for (int i = 0; i < m ; i++) {
for (int j = 0; j < n; j++) {
int valid = arr1[i] == arr2[j] ? 1 : INF;
dp[base][j + 1] = Math.max(dp[base ^ 1][j] + valid,dp[base ^ 1][j + 1]) ;
ans = Math.max(dp[base][j + 1], ans);
}
base ^= 1;
}
return ans;
}
- 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.