583.两个字符串的删除操作
cs
public class Solution {
public int MinDistance(string word1, string word2) {
char[]w1=word1.ToCharArray();
char[]w2=word2.ToCharArray();
int[,]dp=new int[w1.Length+1,w2.Length+1];
for(int i=1;i<=w1.Length;i++)
{
for(int j=1;j<=w2.Length;j++)
{
if(w1[i-1]==w2[j-1])
{
dp[i,j]=dp[i-1,j-1]+1;
}else
dp[i,j]=Math.Max(dp[i-1,j],dp[i,j-1]);
}
}
return word1.Length-dp[w1.Length,w2.Length]+word2.Length-dp[w1.Length,w2.Length];
}
}
代码和最长公共子串一个思路,只是最后返回值要处理一下。
72.编辑距离
cs
public class Solution {
public int MinDistance(string word1, string word2) {
char[]w1=word1.ToCharArray();
char[]w2=word2.ToCharArray();
int[,]dp=new int[w1.Length+1,w2.Length+1];
for(int i=1;i<=w1.Length;i++)
{
dp[i,0]=i;
}
for(int j=1;j<=w2.Length;j++)
{
dp[0,j]=j;
}
for(int i=1;i<=w1.Length;i++)
{
for(int j=1;j<=w2.Length;j++)
{
if(w1[i-1]==w2[j-1])
{
dp[i,j]=dp[i-1,j-1];
}else
dp[i,j]=Math.Min(Math.Min(dp[i-1,j-1],dp[i,j-1]),dp[i-1,j])+1;
}
}
return dp[w1.Length,w2.Length];
}
}
Word1删除一个元素就是Dpij = Dpi - 1j + 1,Word2删除Dpij = Dpij - 1 + 1,替换则是Dpij = dpi - 1j - 1 + 1。