Edit Distance

来源:互联网 发布:win7开机还原软件 编辑:程序博客网 时间:2024/04/24 13:08

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

http://en.wikipedia.org/wiki/Edit_distance

http://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm


动态规划,参看wiki

class Solution {public:    int minDistance(string word1, string word2) {                        int length1 = word1.length();        int length2 = word2.length();        if(length1 == 0 && length2 == 0)            return 0;                int d[length1+1][length2+1];                for(int i = 0 ;i <=length1;i++)            d[i][0] = i;        for(int j = 0; j <=length2;j++)            d[0][j] = j;        for(int i = 1;i<=length1;i++)            for(int j=1;j<= length2;j++)            {                if(word1[i-1] == word2[j-1])                    d[i][j] = d[i-1][j-1];                else                d[i][j] = minimum(d[i-1][j] +1,d[i][j-1]+1,d[i-1][j-1]+1);            }        return d[length1][length2];            }        int minimum(int a,int b,int c)    {        int num1 = min(a,b);        int num2 = min(b,c);                return min(num1,num2);    }};



0 0