Leetcode 72: Edit Distance
Posted Keep walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于Leetcode 72: Edit Distance的主要内容,如果未能解决你的问题,请参考以下文章