给出两个单词word1和word2,计算出将word1转换为word2的最少操作数 (一次操作是指:删除一个字符,或者添加一个字符,或替换一个字符)
编辑距离问题
思路:动态规划
用一个dp数组记录需要变化的步数.dp[i][j]表示字符串长度为i变为字符串长度为j需要的步数
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
/*
给出两个单词word1和word2,计算出将word1转换为word2的最少操作数
(一次操作是指:删除一个字符,或者添加一个字符,或替换一个字符)
*/
static void Main(string[] args)
{
string word1 = "mart";
string word2 = "karma";
int result = Distance(word1, word2);
Console.WriteLine(result);//结果等于3
Console.ReadKey();
}
static int Distance(string word1, string word2)
{
int len1 = word1.Length;
int len2 = word2.Length;
int[,] dp = new int[len1 + 1, len2 + 1];
for (int i = 0; i <= len1; i++)
{
//表示j=0;需要删除i个字符串
dp[i, 0] = i;
}
for (int j = 0; j <= len2; j++)
{
//表示i=0,需要插入j个字符串
dp[0, j] = j;
}
for (int i = 1; i <= len1; i++)
{
for (int j = 1; j <= len2; j++)
{
//如果字符相同则不做变化,等于这个字符之前的步数
if (word1[i - 1] == word2[j - 1])
{
dp[i, j] = dp[i - 1, j - 1];
}
else
{
//否则,就从插入,删除,替换中选择最小的加1
int insert = dp[i, j - 1];
int delete = dp[i - 1, j];
int replace = dp[i - 1, j - 1];
dp[i, j] = Math.Min(Math.Min(insert, delete), replace) + 1;
}
}
}
return dp[len1, len2];
}
}
}
动态规划数组
j=0 | j=1 | j=2 | j=3 | j=4 | j=5 | ||
i=0 | 0 | 1 | 2 | 3 | 4 | 5 | 插入 |
i=1 | 1 | 1 | 2 | 3 | 3 | 4 | |
i=2 | 2 | 2 | 1 | 2 | 3 | 3 | |
i=3 | 3 | 3 | 2 | 1 | 2 | 3 | |
i=4 | 4 | 4 | 3 | 2 | 2 | 3 | |
删除 | 替换 |