Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
b) Delete a character
c) Replace a character
-------------------------------- thinking --------------------------------
How to reduce memory usage?
https://oj.leetcode.com/discuss/10426/my-o-mn-time-and-o-n-space-solution-using-dp-with-explanation
How to solve the problem without using dp?
------------------------------- codes -------------------------------------
class Solution {
public:
int minDistance(string word1, string word2) {
int n1 = word1.size();
int n2 = word2.size();
int dp[n2 + 1][n1 + 1] = {0};
for (int i = 0; i < n1 + 1; i++) {
dp[0][i] = i;
}
for (int j = 0; j < n2 + 1; j++) {
dp[j][0] = j;
}
for (int j = 1; j < n2 + 1; j++) {
for (int i = 1; i < n1 + 1; i++) {
dp[j][i] = min(min(dp[j-1][i]+1, dp[j][i-1]+1), dp[j-1][i-1] + ((word2[j-1]==word1[i-1])?0:1));
}
}
return dp[n2][n1];
}
};
No comments:
Post a Comment