LeetCode Online Judge 题目C# 练习 - Edit Distance

本文介绍如何使用动态规划(DP)算法计算两个字符串之间的最小转换距离,即从一个字符串转换为另一个字符串所需的最少步骤。通过构建二维矩阵并遵循特定的填充规则,可以有效地解决编辑距离问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

"abc" -> "bbdc" : change 'a' to 'b', remove 'd' : 2 steps

 1 public static int MinDistance(string word1, string word2)
 2         {
 3             int[,] matrix = new int[word2.Length + 1, word1.Length + 1];
 4             matrix[0, 0] = 0;
 5 
 6             for (int i = 1; i <= word1.Length; i++) //初始化 第一行
 7                 matrix[0, i] = i;
 8 
 9             for (int i = 1; i <= word2.Length; i++) //初始化 第一列
10                 matrix[i, 0] = i;
11 
12             for(int i = 1; i <= word2.Length; i++)
13             {
14                 for (int j = 1; j <= word1.Length; j++)
15                 {
16                     //如果当前两个字符相等,Min(左上角的数,上面的数+1,左边的数+1)
17                     //如果不相等, Min(左上角的数+1, 上面的数+1,左边的数+1)
18                     int min = Math.Min(matrix[i - 1, j - 1] + (word1[j - 1] == word2[i - 1] ? 0 : 1), matrix[i - 1, j] + 1);
19                     min = Math.Min(min, matrix[i, j - 1] + 1);
20 
21                     matrix[i, j] = min;
22                 }
23             }
24 
25             return matrix[word2.Length, word1.Length];
26         }

 

代码分析:

  这题是典型的字符串比较题,DP最适合。

  建一个matrix(2d-array), size[word1.Length + 1, word2.Length + 1] 因为前面要加上空字符

  例子: "ababd" -> "ccabab"

  先初始化matrix如下。意思是,比如"_" -> "cca" = 2 操作是插入'c','c','a',共3步。 "abab" -> "+ "_" 删除'a','b','a','b',共4 步。

 _ababd
_012345
c1     
c2     
a3     
b4     
a5     
b6     

  然后按照注释里的方法填满表格,返回最后一个数字(最佳解)

 _ababd
_012345
c112345
c222345
a323234
b432323
a543233
b654323

 

补充一个递归的做法,但是不建议。。。

 1         public static int EditDistance(string a, int aLength, string b, int bLength)
 2         {
 3             if (aLength == 0)
 4                 return bLength;
 5             if (bLength == 0)
 6                 return aLength;
 7 
 8             if (a[aLength - 1] == b[bLength - 1])
 9                 return EditDistance(a, aLength - 1, b, bLength - 1);
10             else
11                 return Math.Min(Math.Min(EditDistance(a, aLength - 1, b, bLength - 1) + 1,
12                                 EditDistance(a, aLength - 1, b, bLength) + 1),
13                                 EditDistance(a, aLength, b, bLength - 1) + 1);
14         }

转载于:https://www.cnblogs.com/etcow/archive/2012/08/30/2662985.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值