[关闭]
@laofang 2016-07-17T06:31:31.000000Z 字数 1289 阅读 1177

LeetCode72-编辑距离-C#实现

leetcode


题目:https://leetcode.com/submissions/detail/67380292/

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
Subscribe to see which companies asked this question

参考资料:

参考: http://blog.csdn.net/feliciafay/article/details/17502919
资料: 斯坦福大学自然语言处理第三课-编辑距离

分析:

上面的状态转移方程的含义是,D(i,j)的值,

  • 要么是D(i-1, j)的操作完成之后删除一个字符(第1个单词的第i个字符),
  • 要么是D(i, j-1)的操作完成之后增加一个字符(第2个单词的第j个字符),
  • 要么是D(i-1, j-1)的操作完成自后替换一个字符(如果第1个单词的第i个字符和第2个单词的第j个字符不等),
    或者是D(i-1, j-1)的操作完成自后什么也不做(如果第1个单词的第i个字符和第2个单词的第j个字符相等)

实现代码

  1. public class Solution
  2. {
  3. public int MinDistance(string word1, string word2)
  4. {
  5. int l1 = word1.Length;
  6. int l2 = word2.Length;
  7. int[,] dp = new int[l1+1, l2+1];
  8. for(int i=0; i<=l1; i++)
  9. {
  10. dp[i, 0] = i;
  11. }
  12. for (int j = 0; j <= l2; j++)
  13. {
  14. dp[0, j] = j;
  15. }
  16. for(int i=1; i<=l1; i++)
  17. {
  18. for(int j=1; j<=l2; j++)
  19. {
  20. int min = word2[j-1] == word1[i-1] ? 0 : 1;
  21. dp[i, j] = Math.Min(Math.Min(dp[i - 1, j] + 1, dp[i, j - 1] + 1), min+dp[i-1,j-1]);
  22. }
  23. }
  24. return dp[l1,l2];
  25. }
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注