leetcode || 72、Edit Distance
來源:程序員人生 發布時間:2015-04-17 08:51:21 閱讀次數:3298次
problem:
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted
as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
Hide Tags
Dynamic Programming String
題意:求將字符串word1 轉換為word2 所需最小的步數,操作包括插入、替換和刪除1個字符
thinking:
(1)求全局最優解,鎖定DP法
(2)DP的狀態轉移公式不好找,有幾點是DP法共有的,可以有點啟發:1、DP大都借助數組實現遞推操作 2、DP法的時間復雜度:1維為O(N),2維:O(M*N)
(3)
如果我們用 i 表示當前字符串 A 的下標,j 表示當前字符串 B 的下標。 如果我們用d[i, j] 來表示A[1, ... , i] B[1, ... , j] 之間的最少編輯操作數。那末我們會有以下發現:
1. d[0, j] = j;
2. d[i, 0] = i;
3. d[i, j] = d[i⑴, j - 1] if A[i] == B[j]
4. d[i, j] = min(d[i⑴, j - 1], d[i, j - 1], d[i⑴, j]) + 1 if A[i] != B[j] //分別代表替換、插入、刪除
code:
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int> > f(word1.size()+1, vector<int>(word2.size()+1));
f[0][0] = 0;
for(int i = 1; i <= word2.size(); i++)
f[0][i] = i;
for(int i = 1; i <= word1.size(); i++)
f[i][0] = i;
for(int i = 1; i <= word1.size(); i++)
for(int j = 1; j <= word2.size(); j++)
{
f[i][j] = INT_MAX;
if (word1[i⑴] == word2[j⑴])
f[i][j] = f[i⑴][j⑴];
f[i][j] = min(f[i][j], f[i⑴][j⑴] + 1); //replace
f[i][j] = min(f[i][j], min(f[i⑴][j], f[i][j⑴]) + 1); //delete or insert
}
return f[word1.size()][word2.size()];
}
};
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈