AcWing 902. 最短编辑距离
原题链接
简单
作者:
大海呀大海
,
2020-09-04 08:29:18
,
所有人可见
,
阅读 329
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010;
int n, m;
char a[N], b[N];
int f[N][N];
int main(){
scanf("%d%s", &n, a + 1);
scanf("%d%s", &m, b + 1);
for (int i = 0; i <= m; i ++ ) f[0][i] = i;//a用0个字母,和b匹配只能进行添加的操作
for (int i = 0; i <= n; i ++ ) f[i][0] = i;//初始化f[i][0],用a的前i个字母和b的第0个字符匹配
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ ){
f[i][j] = min(f[i - 1][j] + 1, f[i][j - 1] + 1);//删和增
if (a[i] == b[j]) f[i][j] = min(f[i][j], f[i - 1][j - 1]);//如果当前相等,就不需要操作
else f[i][j] = min(f[i][j], f[i - 1][j - 1] + 1);//如果不相等,就给他换字符(a与b前i-1个字符相同
}
printf("%d\n", f[n][m]);
return 0;
}