[LeetCode] Delete Operation for Two Strings

583. Delete Operation for Two Strings

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int minDistance(string word1, string word2) {
int dp[word1.size() + 1][word2.size() + 1];
for(int i = 0; i <= word1.size(); i++) dp[i][0] = i;
for(int i = 0; i <= word2.size(); i++) dp[0][i] = i;

for(int i = 1; i <= word1.size(); i++)
for(int j = 1; j <= word2.size(); j++)
dp[i][j] = word1[i-1]==word2[j-1] ? dp[i-1][j-1] : 1 + min(dp[i-1][j],dp[i][j-1]);

return dp[word1.size()][word2.size()];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/27/PS/LeetCode/delete-operation-for-two-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.