72. Edit Distance , LeetCode

来源:互联网 发布:genesis软件 编辑:程序博客网 时间:2024/06/14 21:00

题目:

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

思路:

动态规划,dp[i][j] s1前i(包括i)个字符与s2前j个(包括j)字符的最短编辑距离。
那么当s1[i] != s2[j]时, dp[i][j] = min(dp[i - 1][j - 1] + 1, min(dp[i][j - 1] + 1, dp[i - 1][j] + 1));

代码:

int minDistance(string s1, string s2) {                int len1 = s1.size();int len2 = s2.size();    if(len1 == 0 || len2 == 0)return len1 + len2;vector<vector<int> > dp(len1);for (int i = 0; i < len1; i++)dp[i].assign(len2, numeric_limits < int >::max());if (s1[0] == s2[0])dp[0][0] = 0;//a:这里0表示第一字符elsedp[0][0] = 1;for (int j = 1; j < len2; j++)dp[0][j] = j;//b:这里认为s1中没有字符,即认为0表示第-1个字符,与a处相矛盾for (int i = 1; i < len1; i++)dp[i][0] = i;for (int i = 1; i < len1; i++)for (int j = 1; j < len2; j++){if (s1[i] == s2[j])dp[i][j] = dp[i - 1][j - 1];elsedp[i][j] = min(dp[i - 1][j - 1] + 1, min(dp[i][j - 1] + 1, dp[i - 1][j] + 1));}return dp[len1 - 1][len2 - 1];    }
看似上述代码没什么问题,但是submit之后 Wrong Answer,原因就在于上面红字的地方。错误很细微,,下面是AC代码
总结,写代码时候一定要时刻明确dp的概念\含义。

发送 

class Solution {public:    int minDistance(string s1, string s2) {            int len1 = s1.size() + 1;int len2 = s2.size() + 1;    vector<vector<int> > dp(len1);for (int i = 0; i < len1; i++)dp[i].assign(len2, numeric_limits < int >::max());for (int j = 0; j < len2; j++)dp[0][j] = j;for (int i = 0; i < len1; i++)dp[i][0] = i;for (int i = 1; i < len1; i++)for (int j = 1; j < len2; j++){if (s1[i - 1] == s2[j - 1])<span style="color:#ff0000;">// c这里也需要注意</span>dp[i][j] = dp[i - 1][j - 1];elsedp[i][j] = min(dp[i - 1][j - 1] + 1, min(dp[i][j - 1] + 1, dp[i - 1][j] + 1));}return dp[len1 - 1][len2 - 1];    }};


0 0
原创粉丝点击