Leetcode 72: 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

 

 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 }

 

posted @ 2017-11-10 11:55  逸朵  阅读(103)  评论(0编辑  收藏  举报