LintCode-編輯距離

給出兩個單詞word1和word2,計算出將word1 轉換爲word2的最少操作次數。

你總共三種操作方法:

  • 插入一個字符
  • 刪除一個字符
  • 替換一個字符

您在真實的面試中是否遇到過這個題? 
Yes
樣例

給出 work1="mart" 和 work2="karma"

返回 3

標籤 Expand  

相關題目 Expand 


分析:經典的動態規劃面試題,在有道的實習面中遇到過,用dp[i][j]表示第一個字符串到i第二個字符串到j的時候需要進行多少次修改。

代碼:

class Solution {
public:    
    /**
     * @param word1 & word2: Two string.
     * @return: The minimum number of steps.
     */
    int minDistance(string word1, string word2) {
        // write your code here
        int n = word1.length();
        int m = word2.length();
        vector<vector<int> > dp(n+1,vector<int>(m+1,0));
        for(int i = 1;i<=n;i++)
            dp[i][0]=i;
        for(int i=1;i<=m;i++)
            dp[0][i]=i;
        for(int i=1;i<=n;i++)
        {
            char c1 = word1[i-1];
            for(int j=1;j<=m;j++)
            {
                char c2 = word2[j-1];
                if(c1==c2)
                    dp[i][j] = dp[i-1][j-1];
                else
                    dp[i][j] = min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1;
                
            }
        }
        return dp[n][m];
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章