Edit Distance

来源:互联网 发布:diagbox软件 编辑:程序博客网 时间:2024/04/25 08:33

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

解法:动态规划:对于串word1[1,i]和word2[1,j],如果word1[i]==word2[j],则距离等于两个字符串去掉最后一个字母的距离;如果不相等,有三种操作,word1去掉i,word1[1,i-1]和word2[1,j]比较;word2去掉j,word1[1,i]和word2[1,j-1]比较;word1[i]改成word2[j],word1[1,i-1]和word2[1,j-1]比较,都需要额外一步操作。

class Solution {public:    int minDistance(string word1, string word2) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int m = word1.length();        int n = word2.length();                int dis[m+1][n+1];                for(int i = 0;i <= m;i++)            dis[i][0] = i;                for(int j = 0; j <= n;j++)            dis[0][j] = j;                    for(int i = 1; i<= m;i++)        {            for(int j = 1;j<=n;j++)            {                if(word1[i-1] == word2[j-1]){                    dis[i][j] = dis[i-1][j-1];                }else{                    dis[i][j] = min(dis[i-1][j],dis[i][j-1])+1;                    dis[i][j] = min(dis[i][j],dis[i-1][j-1]+1);                }            }        }                return dis[m][n];                    }};
80 milli secs.