leetcode Edit Distance

作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4051082.html

题目链接:leetcode Edit Distance

最短编辑距离,简单dp,dp[i,j]表示到str1的第i个字符和str2的第j个字符止的最短编辑距离。

dp[i,j] = min(dp[i-1,j-1]+ !(str1[i]==str2[j]), dp[i-1,j]+1, dp[i,j-1]+1)

注意二维动态vector的神奇定义方式:

vector<vector<int> > dp(word1.size()+1, vector<int> (word2.size()+1));

代码如下:

 1 class Solution {

 2 public:

 3         int minDistance(string word1, string word2) {

 4         vector<vector<int> > dp(word1.size()+1, vector<int> (word2.size()+1));

 5         for( int i = 0 ; i <= word1.size() ; i++ )

 6         {

 7             dp[i][0] = i;

 8         }

 9         for( int i = 0 ; i <= word2.size() ; i++ )

10         {

11             dp[0][i] = i;

12         }

13         for( int i = 0 ; i < word1.size() ; i++ )

14         {

15             for( int j = 0 ; j < word2.size() ; j++ )

16             {

17                 int tmp;

18                 if( word1[i] == word2[j] ) tmp = 0;

19                 else tmp = 1;

20                 dp[i+1][j+1] = min(dp[i][j]+tmp, min(dp[i][j+1]+1, dp[i+1][j]+1));

21             }

22         }

23         return dp[word1.size()][word2.size()];

24     }

25 };
View Code

 

你可能感兴趣的:(LeetCode)