Thoughts on leetcode 1143
Let A=“a0,a1,…,am”,B=“b0,b1,…,bn”,and Z=“z0,z1,…,zk” is their longest common sequence. Then, we have:
- if am = bn,then zk = am = bn,and “z0,z1,…,z(k-1)” is the longest common sequence of “a0,a1,…,a(m-1)” and “b0,b1,…,b(n-1)”
- if am != bn, then if zk != am, “z0,z1,…,z(k)” is the longest common sequence of “a0,a1,…,a(m-1)” and “b0,b1,…,bn”
- if am != bn, then if zk != bn, “z0,z1,…,z(k)” is the longest common sequence of “a0,a1,…,a(m)” and “b0,b1,…,b(n - 1)”
Solution to Leetcode 1143
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int n1 = text1.length();
int n2 = text2.length();
int[][] dp = new int[n1 + 1][n2 + 1];
for(int i = 0; i < n1 + 1; i++){
for(int j = 0; j < n2 + 1; j++){
if(i == 0 || j == 0){
dp[i][j] = 0;
}
else{
//minus one to match the index
if(text1.charAt(i - 1) == text2.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[n1][n2];
}
}
Thoughts on leetcode 1035
https://leetcode.com/problems/uncrossed-lines/
dp[i][j] represents the longest common subsequence between nums1[0 : i] and nums2[0 : j]
if nums1[i] = nums2[j] : dp[i][j] = dp[i-1][j-1] + 1
if nums1[i] != nums2[j] : dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j])
Solution for leetcode 1035
class Solution {
public int maxUncrossedLines(int[] nums1, int[] nums2) {
int n1 = nums1.length;
int n2 = nums2.length;
int[][]dp = new int[n1 + 1][n2 + 1];
for(int i = 1; i < n1 + 1; i++){
for(int j = 1; j < n2 + 1; j++){
if(nums1[i - 1] == nums2[j -1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else{
dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
}
}
}
return dp[n1][n2];
}
}
Thoughts on leetcode 1092
The LCS needs to be inserted into the output only once. Other characters in the output need to keep the order as in str1 and str2.
if(i > 0 && dp[i][j] == dp[i-1][j]){
sb.insert(0, str1.charAt(i-1));
i--;
}
This means that the ith character in str1 is not in LCS, therefore, we add it to the output directly.
Solution for leetcode 1092
https://leetcode.com/problems/shortest-common-supersequence/
class Solution {
public String shortestCommonSupersequence(String str1, String str2) {
//first part (same as LCS)
int n = str1.length();
int m = str2.length();
int[][] dp = new int[n + 1][m + 1];
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; 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]);
}
}
}
//second part: construct the string
StringBuilder sb = new StringBuilder();
for(int i = n, j = m; i>0 || j>0;){
if(i > 0 && dp[i][j] == dp[i-1][j]){
sb.insert(0, str1.charAt(i-1));
i--;
}
else if(j > 0 && dp[i][j] == dp[i][j-1]){
sb.insert(0, str2.charAt(j-1));
j--;
}
else{
sb.insert(0, str2.charAt(j-1));
i--;
j--;
}
}
return sb.toString();
}
}