内容:给出一个长度为n的字符串A,再给出一个长度为m的字符串B,求出字符串A变字符串B的最少编辑次数即最小编辑距离。
目的:熟悉动态规划的步骤
1、问题结构分析
先设D[n,m]为字符串A[1,n]变为B[1,m]的最小编辑距离,用来存放最优解。
2、递推关系的建立(分析最优结构)
书写伪代码:
n←length(A)
m←length(B)
for i←0 to n do
D[i,0] ←i
for j←0 to m do
D[0,j] ←j
for i←1 to n do
for j←1 to m do
c←0
if Ai≠Bj then
c←1
re←D[i-1,j-1]+c
de←D[i-1,j]+1
in←D[i,j-1]+1
if re=min{de,in,re}then
D[i,j] ←D[i-1,j-1]+c
else if in= min{de,in,re}then
D[i,j] ←D[i,j-1]+1
else
D[i,j] ←D[i-1,j]+1
举例分析:A:fxpimu,B:xwr
代码运行结果:
字符串A长度为n,B长度为m时,两重循环嵌套,有n*m个子问题,每个子问题的算法时间复杂度为常数,故总的时间复杂度为 O(mn); 且由于使用了辅助二维数组D[][], 所以空间复杂度为O(mn)。
代码:
#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
using namespace std;
int D[2001][2001];
int main(){
char A[2001],B[2001];
int i,j;
cin>>A>>B;
int n=strlen(A);
int m=strlen(B);
for(i=0;i<=n;i++)
{
D[i][0]=i;
}
for(j=0;j<=m;j++){
D[0][j]=j;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
int c=0;
if(A[i]!=B[j])
{
c=1;
}
int re=D[i-1][j-1]+c;
int de=D[i-1][j]+1;
int in=D[i][j-1]+1;
if(re==min(de,min(in,re)))
{
D[i][j]=D[i-1][j-1]+c;
}
else if(in==min(de,min(in,re)))
{
D[i][j]=D[i][j-1]+1;
}
else
{
D[i][j]=D[i-1][j]+1;
}
}
}
cout<<D[n][m]<<endl;
return 0;
}