【动态规划】计算字符串编辑距离

题目

设A 和B 是2 个字符串。要用最少的字符操作将字符串A 转换为字符串B。这里所说的字符操作包括 (1)删除一个字符; (2)插入一个字符; (3)将一个字符改为另一个字符。 将字符串A变换为字符串B 所用的最少字符操作数称为字符串A到B 的编辑距离,记为d(A,B)。试设计一个有效算法,对任给的2 个字符串A和B,计算出它们的编辑距离d(A,B)。

输入

 
   

第一行是字符串A,文件的第二行是字符串B。字符串长度不大于2000。

输出

 
   

输出距离d(A,B)

样例输入

fxpimu
xwr

样例输出

5

思路:开一个DP数组[i][j],表示ai与bi两个字符串之间的编辑距离,考虑字符串之间进行删除、插入、替换操作的开销,写出状态转移方程,随后求出最小开销即可

代码如下:

#include <stdio.h>    
#include<iostream> 
#include <string.h>
#include <algorithm>
using namespace std;   
#define N 2005    
char s1[N],s2[N]; 
int d[N][N];     
void editDistance(int len1,int len2) {     
     //这里其实要动态分配  
    int i,j;     
    for(i = 0;i <= len1;i++)     
        d[i][0] = i;   //i从第1个开始,表示第1个字母,所以第0个没算  
    for(j = 0;j <= len2;j++)     
        d[0][j] = j;     
    for(i = 1;i <= len1;i++)     
        for(j = 1;j <= len2;j++) {     
            int deletion = d[i-1][j] + 1;     
            int insertion = d[i][j-1] + 1;   
			int replaces;  
            if(s1[i-1]==s2[j-1])  
            {  
                replaces=d[i-1][j-1];  
            }  
            else  
            {  
                replaces=d[i-1][j-1]+1;  
            }       
            d[i][j] = min(min(deletion,insertion),replaces);     
        }     
    printf("%d\n",d[len1][len2]);     
}
int main()
{
     while(cin>>s1>>s2)  
    {   
    int a=strlen(s1),b=strlen(s2) ;
    editDistance(a,b);
}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36793206/article/details/80317266