首页 > 代码库 > [leetcode]Edit Distance

[leetcode]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

意思是求字符串编辑距离(Edit Distance),编辑距离是指两个字符串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括
  a)插入一个字符
  b)删除一个字符
  c)将一个字符替换成另一个字符
比如:tea->eat 最小两步。
分析过程:假设两个字符串是S和T,枚举字符串S和T最后一个字符s[i]、t[j]对应的四种情况:(字符-字符)(字符-空白)(空白-字符)(空白-空白);显然的是,(空白-空白)必然是多余的编辑操作。
  (1)S + 空白
      T + 字符X
      那么,S变成T,最后,在S的末尾插入“字符X”
  dp[i,j] = dp[i,j-1] + 1
 
  (2)S + 字符X
    T + 字符Y
    S变成T,最后,在X修改成Y
         dp[i,j] = dp[i-1,j-1] + (X==Y ? 0 : 1)
     (3)S + 字符X
      T + 空白
      S变成T,X被删除
      dp[i,j] = dp[i-1,j] + 1
  用dp[i][j] 表示第一个串S[0…i] 和第2个串T[0…j] 的最短编辑距离。  
  那么    if(S[i]==T[j])
       dp[i][j] = min(dp[i-1][j-1],dp[i][j-1]+1,dp[i-1][j-1]+1)
      else
                  dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1
最后代码如下:
class Solution {public:    int minDistance(string word1, string word2) {		int len1 = word1.length();		int len2 = word2.length();		if(len1 == 0) return len2;		if(len2 == 0) return len1;		int i,j;		vector<vector<int> > dp(len1 + 1, vector<int>(len2 + 1));		for(i = 0; i <= len1; i++)		{			dp[i][0] = i;		}		for(j = 0; j <= len2; j++)		{			dp[0][j] = j;		}		for(i = 1; i <= len1; i++)		{			for(j = 1; j <= len2; j++)			{				/*int cost = (word1[i-1] == word2[j - 1]) ? 0 : 1;				dp[i][j] = min(dp[i-1][j-1]+cost,min(dp[i-1][j]+1,dp[i][j-1]+1));*/				if(word1[i-1] == word2[j - 1])				{					dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]) + 1);				}else{					dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1])) + 1;				}			}		}		return dp[len1][len2];    }};

  

 
 

[leetcode]Edit Distance