LeetCode 72 Edit Distance
阿新 • • 發佈:2022-05-10
Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Solution
設 \(dp[i][j]\) 表示將 word1
的 \([0,...,i)\) 轉變為 word2
的 \([0,...,j)\)
現考慮轉移:假設現在已經知道了 \(dp[i][j]\) 之前的所有狀態最小運算元,如果 \(s1[i]==s2[j]\),則直接:
\[dp[i][j] = dp[i-1][j-1] \]否則,則是考慮三個操作所帶來的花費:
- 最簡單的就是 replace: \(dp[i][j] = dp[i-1][j-1]+1\)
- 如果 \(s1[0,...,i-1) =s2[0,...,j)\),則直接 delete \(s[i-1]\):
- 如果 \(s1[0,...,i)+s2[j-1]=s2[0,...,j)\)
點選檢視程式碼
class Solution { private: int dp[505][505]; public: int minDistance(string word1, string word2) { int n = word1.length(), m = word2.length(); // dp[i][j]: word1[0,...,i) word2[0,...,j) for(int i=0;i<=n;i++)dp[i][0] = i; for(int i=0;i<=m;i++)dp[0][i] = i; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(word1[i-1]==word2[j-1])dp[i][j] = dp[i-1][j-1]; else{ // word1[i-1]!=word2[j-1] // dp[i-1][j-1] is known now // Replace: dp[i][j] = dp[i-1][j-1]+1; // Delete: dp[i][j] = dp[i-1][j]+1; // Insert: dp[i][j] = dp[i][j-1]+1; dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1; } } } return dp[n][m]; } };