最小编辑距离

来源:互联网 发布:网络云课堂 编辑:程序博客网 时间:2024/05/16 07:21

问题

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


思路

网上有的版本说的是要在word2上面做操作,不敢苟同

言归正传,本题采用动态规划的算法,用d[ i ][ j ],表示word1中前i个字符和word2中前j个字符的编辑距离;

情况就可以分成以下几种,d[ i ][ j ] 是以下几种情况的最小值:

情况1 、

d[ i-1 ][ j ] ,我们已经求得了word1的前 i - 1 个字符到 word 2 的前 j个字符花费的步长,那么,要得到 word1 的前 i  个字符到 j 个字符的步长,只需要将word1 中减去一个字符就然后加上  d[ i-1 ][ j ]  就可以了,也就是d[ i ][ j ] = d[ i-1 ][ j ] + cost( delete word1.delete(word1[i]) ) 

情况2 、

d[ i1 ][ j-1 ]我们已经求得了word1的前 i 个字符到 word2 的前 j - 1 个字符花费的步长,那么,要得到 word1 的前 i  个字符到 j 个字符的步长,只需要将word1 中减去一个字符就然后加上  d[ i-1 ][ j ]  就可以了, 也就是d[ i ][ j ] = d[ i ][ j - 1 ] + cost(  word1.insert( word2[ j ] ) ) 

情况3 、

d[ i-1][ j-1 ]  我们已经求得了word1的前i-1个字符到word2的前j-1个字符花费的步长,那么 如果word1[ i ] == word2[ j ] ,则d[ i ][ j ] =d[ i-1][ j-1 ]  , 否则 将word1[ i ] 替换成为 word2[ j ]即可。 也就是d[ i ][ j ] = d[ i - 1 ][ j  - 1 ] + A  , 当word1[ i ] == word2[ j ] , A=0 ,否则 A = cost(word1.changer(word1[ i ] to word2[ j ])

代码大概长成这个样子

class Solution {public:int min(int i , int j , int k){int rt = i < j ? i : j;rt = rt < k ? rt : k;return rt;}    int minDistance(string word1, string word2) {int len1 = word1.length() + 1;int len2 = word2.length() + 1;const int INSERT_COST = 1;const int DELETE_COST = 1;const int CHANGE_COST = 1;vector< vector <int > > d;for(int i = 0  ; i < len1 ; i++){vector<int> vec(len2 , 0);d.push_back(vec);}for(int i = 0 ; i < len2 ; i++){d[0][i] = i*INSERT_COST;}for(int i = 0 ; i < len1 ; i++){d[i][0] = i*DELETE_COST;}for(int i = 1 ; i < len1 ; i++){for(int j = 1 ; j < len2  ; j++){int change_cost = word1.at(i-1) == word2.at(j-1) ? d[i-1][j-1] : d[i-1][j-1] + CHANGE_COST;d[i][j] = min( d[i-1][j] + DELETE_COST, d[i][j-1] + INSERT_COST , change_cost);}}return d[len1-1][len2-1];    }};

 


0 0
原创粉丝点击