pg

Original question

Example:
input: strings “AGGTAB” and “GXTXAYB”
output: 4


Two cases:
string S and T, m = S.length + 1, n = T.length + 1
dp[i][j] records the length of longest common subsequence between S[0..i] and T[0..j]

  1. S[i] == T[j] then dp[i][j] = dp[i-1][j-1] + 1
  2. S[i] != T[j] then dp[i][j] = max(dp[i-1][j], dp[i][j-1])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int (string S, string T){
int slen = (int)S.length();
int tlen = (int)T.length();
vector<vector<int>> dp(slen+1, vector<int>(tlen+1, 0));
for(int i = 0; i < slen; i++){
for(int j = 0; j < tlen; j++){
if(S[i] == T[j])
dp[i+1][j+1] = dp[i][j] + 1;
else
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
}
}
return dp[slen][tlen];
}

LC 583. Delete Operation for Two Strings

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Input: “sea”, “eat”
Output: 2
Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.

The question can be inverted to find the longest common subsequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int minDistance(string word1, string word2) {
int len1 = word1.length();
int len2 = word2.length();
vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));
for(int i = 0; i < len1; i++){
for(int j = 0; j < len2; j++){
if(word1[i] == word2[j])
dp[i+1][j+1] = dp[i][j] + 1;
else
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
}
}
return len1 + len2 - 2*dp[len1][len2];
}