第十五周LeetCode

来源:互联网 发布:最后一炮优化很烂 编辑:程序博客网 时间:2024/06/05 11:59

题目
Edit Distance
难度 hard

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

实现思路

这个题是书上的例题。假设E[i][j]表示把word1的前i个字符与word2的前j个字符对齐所需的最小操作,最右端有三种对齐方式:
*        P        P
O       *        O

*表示占位符,第一种情况表示dp[i][j]为dp[i-1][j]+1,第二种情况表示dp[i][j]为dp[i][j-1]+1,第三种情况,如果O和P相等,那么不需要操作,否则需要进行替换操作。因此dp[i][j]=min(dp[i][j-1]+1,dp[i-1][j]+1,dp[i-1][j-1]+(int)(word1[i-1]!=word2[j-1]))。

实现代码

int minDistance(string word1, string word2) {        vector<vector<int>> E(word1.length()+1,vector<int>(word2.length()+1,0));        for (int i = 0; i <= word1.length(); i++) {            E[i][0] = i;        }        for (int j = 0; j <= word2.length(); j++) {            E[0][j] = j;        }        for (int i = 1; i <= word1.length(); i++) {            for (int j = 1; j <= word2.length(); j++) {                int x = E[i-1][j]+1;                int y = E[i][j-1]+1;                int z = E[i-1][j-1]+(int)(word1[i-1]!=word2[j-1]);                E[i][j]=min(min(x,y),z);            }        }        return E[word1.length()][word2.length()];    }
原创粉丝点击