leetcode 編輯距離(動態規劃)

給定兩個單詞 word1 和 word2,計算出將 word1 轉換成 word2 所使用的最少操作數 。

你可以對一個單詞進行如下三種操作:

插入一個字符
刪除一個字符
替換一個字符
示例 1:

輸入: word1 = "horse", word2 = "ros"
輸出: 3
解釋:
horse -> rorse (將 'h' 替換爲 'r')
rorse -> rose (刪除 'r')
rose -> ros (刪除 'e')
示例 2:

輸入: word1 = "intention", word2 = "execution"
輸出: 5
解釋:
intention -> inention (刪除 't')
inention -> enention (將 'i' 替換爲 'e')
enention -> exention (將 'n' 替換爲 'x')
exention -> exection (將 'n' 替換爲 'c')
exection -> execution (插入 'u')

 

題解:編輯距離是典型的動態規劃問題。

首先,我們考慮對於s1的每一個字符,有四種選擇,什麼都不做,替換,刪除,添加;

假設dp[i][j]表示第一個字符串的前i個字符和s2的前j個字符變成相同所需要的最少操作次數。

if(s1[i]==s2[j]) dp[i][j]=dp[i-1][j-1];

else

  dp[i][j]=min{

        dp[i-1][j],  // 把s1的第i個字符刪除

        dp[i][j-1],  //在s1中插入一個字符

        dp[i-1][j-1],吧s1的第i字符替換

  };

參考代碼:

 1 class Solution {
 2 public:
 3     int minDistance(string word1, string word2) 
 4     {
 5         int n=word1.length(),m=word2.length();
 6         if(n==0) return m;
 7         if(m==0) return n;
 8         int dp[n+1][m+1]={0};
 9         for(int i=1;i<=n;++i) dp[i][0]=i;
10         for(int j=1;j<=m;++j) dp[0][j]=j;
11 
12         for(int i=1;i<=n;++i)
13             for(int j=1;j<=m;++j)
14             {
15                 if(word1[i-1]==word2[j-1])
16                     dp[i][j]=dp[i-1][j-1];
17                 else
18                     dp[i][j]=min(dp[i-1][j]+1,min(dp[i][j-1]+1,dp[i-1][j-1]+1));
19             } 
20         return dp[n][m];
21     }
22 };
C++

 

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