这道题目在洛谷和牛客上都有,牛客网上的题目稍微复杂一点点,就是删除、替换插入的代价不同,我先讲一下洛谷上操作代价相同的,再讲一下操作代价不同的
1.洛谷P2758 编辑距离
我们用dp[i][j]表示把长度为i的字符串A转成长度为j的字符串B所需要的代价
- 如果strA[i-1]==strB[j-1],那么只需要考虑strA[0~(i-2)]转成strB[0~(j-2)]的代价,也就是dp[i][j]=dp[i-1][j-1]
- 如果strA[i-1]!=strB[j-1],那么有以下3种方法可以把strA[0~(i-2)]转成strB[0~(j-2)]
- 1.把strA[i-1]替换成strB[j-1]的那个字母,然后只需要考虑strA[0~(i-2)]转成strB[0~(j-2)]的代价,也就是dp[i][j]=1+dp[i-1][j-1]
- 2.把strA[i-1]删掉,保持strB不变,那么就需要考虑把strA[0~(i-2)]转成strB[0~(j-1)]的代价,也就是dp[i][j]=1+dp[i-1][j]
- 3.在strA[i-1]的位置上插入strB[j-1]的这个字符,并且把strA[0~(i-1)]整体往前移一个位置,那么就需要考虑把strA[0~(i-1)]转成strB[0~(j-2)]所需要的代价,也就是dp[i][j]=1+dp[i][j-1]
我的代码用的是压缩数组,如果暂时看不懂可以按上面介绍的思路用二维数组进行求解
AC代码如下:
#include <bits/stdc++.h>
using namespace std;
string a,b;
const int maxn=2005;
int dp[maxn];
int main(){
cin>>a>>b;
int lena=a.size();
int lenb=b.size();
for(int i=0;i<=lenb;i++){
dp[i]=i;
}
for(int i=1;i<=lena;i++){
int tmp=dp[0];
dp[0]=i;
for(int j=1;j<=lenb;j++){
int pre=tmp;
tmp=dp[j];
if(a[i-1]==b[j-1])
dp[j]=pre;
else{
dp[j]=min(min(pre,dp[j-1]),dp[j])+1;
}
}
}
printf("%d\n",dp[lenb]);
}
2.牛客网 最小编辑代价
在这道题中,删除的代价是dc,替换的代价是rc,插入的代价是ic
由于删除、替换、插入的代价不同,而一次替换相当于删除+插入,所以需要先判断,是直接替换的代价低,还是先删后插的代价低:
rc=min(rc, dc+ic);
状态转移方程也会发生相应的变化,但总体思想仍然不变:
我们用dp[i][j]表示把长度为i的字符串A转成长度为j的字符串B所需要的代价
- 如果strA[i-1]==strB[j-1],那么只需要考虑strA[0~(i-2)]转成strB[0~(j-2)]的代价,也就是dp[i][j]=dp[i-1][j-1]
- 如果strA[i-1]!=strB[j-1],那么有以下3种方法可以把strA[0~(i-2)]转成strB[0~(j-2)]
- 1.把strA[i-1]替换成strB[j-1]的那个字母,然后只需要考虑strA[0~(i-2)]转成strB[0~(j-2)]的代价,也就是dp[i][j]=rc+dp[i-1][j-1]
- 2.把strA[i-1]删掉,保持strB不变,那么就需要考虑把strA[0~(i-2)]转成strB[0~(j-1)]的代价,也就是dp[i][j]=dc+dp[i-1][j]
- 3.在strA[i-1]的位置上插入strB[j-1]的这个字符,并且把strA[0~(i-1)]整体往前移一个位置,那么就需要考虑把strA[0~(i-1)]转成strB[0~(j-2)]所需要的代价,也就是dp[i][j]=ic+dp[i][j-1]
初始化的方式也变了,具体可看我的代码注释
class Solution {
public:
/**
* min edit cost
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @param ic int整型 insert cost
* @param dc int整型 delete cost
* @param rc int整型 replace cost
* @return int整型
*/
int minEditCost(string str1, string str2, int ic, int dc, int rc) {
//直接修改和删除后再添加的效果相同
rc=min(rc, dc+ic);
int dp[5005]={0};
int len1=str1.size();
int len2=str2.size();
dp[0]=0;
//相当于把长度为0的字符串转成长度为i的字符串所付出的代价,那么就是不断地插入
for(int i=1;i<=len2;i++){
dp[i]=dp[i-1]+ic;
}
for(int i=1;i<=len1;i++){
//对于每一次i循环而言,
//上一次循环得到的dp[i-1],相当于已经转成了长度为i的字符串
//而要初始化这一次的dp[0],就需要把上一次循环中得到的长度为i的字符串删干净
//由于有i个字符,所以要删i次
int tmp=dp[0];
dp[0]=dc*i;
for(int j=1;j<=len2;j++){
int pre=tmp;
tmp=dp[j];
if(str1[i-1]==str2[j-1])
dp[j]=pre;
else{
dp[j]=min(min(dp[j]+dc,pre+rc),ic+dp[j-1]);
}
}
}
return dp[len2];
}
};