LeetCode 72. 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

题目大意就是将字符串word1变为word2需要几步操作。

每一步操作都有三种情况 -- 插入,删除,转换

  • 建立dp数组
  • dp[i][j]等于将word1[0,1,2...,i-1]转化为word2[0,1,2...,j-1]最少需要多少步操作
  • 那么分为两种情况
  • 插入和删除(如果字符串word2中有字符串word1中没有的字符,那么对于这个字符,可以在字符串word1中插入这个,也可以在字符串word2中删除这个字符;所以插入和删除为一类情况)
  • 转化
  • 这两步对应的情况分别为:
//如果word1[i] != wordw[j]
//对于第一步 dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + 1;
//对于第二部 dp[i][j] = dp[i-1][j-1] + 1;
//所以将这两种结合,取较小值。

if(word1[i] != wordw[j])
    dp[i][j] = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])) + 1;

代码如下:

class Solution {
public:
    int minDistance(string word1, string word2) {
    	int x = word1.size(), y = word2.size();
    	if(x == 0)
    		return y;
    	if(y == 0)
    		return x;
        vector<vector<int>>dp(x+1, vector<int>(y+1, 0));
        for(int i=0; i<x+1; ++ i)
        	dp[i][0] = i;
        for(int i=0; i<y+1; ++ i)
        	dp[0][i] = i;

        for(int i=1; i<x+1; ++ i)
        {
        	for(int j=1; j<y+1; ++ j)
        	{
        		if(word1[i-1] == word2[j-1])
        			dp[i][j] = dp[i-1][j-1];
        		else
        			dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;
        	}
        }
        return dp[x][y];
    }
};
posted @ 2017-04-12 20:13  aiterator  阅读(83)  评论(0编辑  收藏  举报