# leetcode #72 in cpp

46人阅读 评论(0)

Solution:

We use DP where dp[i][j] represents minimum steps from word1[0...i-1] to words2[0...j-1]

Code:

class Solution {
public:
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));//dp[i][j]-->min step convert word1[0..i-1] to word2[0...j-1]
dp[0][0] = 0;
for(int i = 1; i < len2+1; i ++){
dp[0][i] = i;
}
for(int i = 1; i< len1 + 1; i ++){
dp[i][0] = i;
}

for(int i = 1; i < len1+1; i++){
for(int j = 1; j < len2 + 1; j ++){
if(word1[i-1] == word2[j-1]){
dp[i][j] = dp[i-1][j-1];
}else{
//delete word1[i-1] and make word1[0...i-2] to word2[0..j-1], or replace word1[i-1] with word2[j-1]
int mini = min(dp[i-1][j], dp[i-1][j-1]);
//make word1[0...i-1] to word2[0...j-2], insert word2[j-1] into word1
mini = min(mini, dp[i][j-1]);
dp[i][j] = mini + 1;
}
}
}
return dp[len1][len2];
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：6896次
• 积分：1393
• 等级：
• 排名：千里之外
• 原创：139篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档
阅读排行
评论排行