首页 > 其他 > 详细

Leetcode 72: Edit Distance

时间:2017-11-10 12:30:52      阅读:175      评论:0      收藏:0      [点我收藏+]

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

 

 1 public class Solution {
 2     public int MinDistance(string word1, string word2) {
 3         int m = word1.Length, n = word2.Length;
 4         
 5         if (m == 0) return n;
 6         if (n == 0) return m;
 7         
 8         var dp = new int[m + 1, n + 1];
 9         for (int i = 0; i < m + 1; i++)
10         {
11             for (int j = 0; j < n + 1; j++)
12             {
13                 if (i == 0)
14                 {
15                     dp[i, j] = j;
16                 }
17                 else if (j == 0)
18                 {
19                     dp[i, j] = i;
20                 }
21                 else
22                 {
23                     if (word1[i - 1] == word2[j - 1])
24                     {
25                         dp[i, j] = dp[i - 1, j - 1];
26                     }
27                     else
28                     {
29                         dp[i, j] = Math.Min( Math.Min(dp[i - 1, j] + 1, dp[i, j - 1] + 1), dp[i - 1, j - 1] + 1);
30                     }
31                 }
32             }
33         }
34         
35         return dp[m, n];
36     }
37 }

 

Leetcode 72: Edit Distance

原文:http://www.cnblogs.com/liangmou/p/7813884.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!