Leetcode題解:十幾行程式碼計算編輯距離
阿新 • • 發佈:2018-12-05
題目要求
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
求解思路
這是一個經典的動態規劃問題了,以前做DNA序列比較時也完成過。
假設:
狀態轉移方程:
狀態初始化
原始碼
有兩點需要注意,一個是字串的下標需要-1,另一個是diff的實現方式,如果寫成我一開始提交的版本即
int(word1[i-1]!=word2[j-1])
,執行速度會非常之慢,還是寫成(word1[i-1]!=word2[j-1] ? 1 : 0)
為好
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
vector <vector <int>> E (m+1, vector<int>(n+1, 0));
for (int i = 0; i < n+1; i++) {
E[0][i] = i;
}
for (int j = 1; j < m+1; j++) {
E[j][0] = j;
}
for (int i = 1; i < m+1; i++) {
for (int j = 1; j < n+1; j++) {
E[i][j] = min(1+min(E[i-1][j], E[i][j-1]), E[i-1][j-1]+(word1[i-1]!=word2[j-1] ? 1 : 0));
}
}
return E[m][n];
}
};
滿意了滿意了