Edit Distance

来源:互联网 发布:sai软件认识 编辑:程序博客网 时间:2024/06/17 23:42

Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character

b) Delete a character
c) Replace a character

经典动态规划解法:

分析

设状态为f[i][j],表示A[0,i] 和B[0,j] 之间的最小编辑距离。设A[0,i] 的形式是
str1c,B[0,j] 的形式是str2d,
1. 如果c==d,则f[i][j]=f[i-1][j-1];
2. 如果c!=d,
(a) 如果将c 替换成d,则f[i][j]=f[i-1][j-1]+1;
(b) 如果在c 后面添加一个d,则f[i][j]=f[i][j-1]+1;
(c) 如果将c 删除,则f[i][j]=f[i-1][j]+1;

 int minDistance(string word1, string word2) {const size_t m =word1.size();const size_t n =word2.size();int f[m+1][n+1];/*for (int i=0;i<=m;i++){f[i] =new int[n+1];}*/for (int i=0;i<=m;i++){f[i][0] =i;}for (int j=0;j<=n;j++){f[0][j] =j;}for (int i=1;i<=m;i++){for (int j=1;j<=n;j++){if (word1[i-1] ==word2[j-1]){f[i][j] =f[i-1][j-1];}else{int mn =min(f[i-1][j],f[i][j-1]);f[i][j] =1+min(mn ,f[i-1][j-1]);}}}return f[m][n];}


0 0