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
thinking:
(1)求全局最优解,锁定DP法
(2)DP的状态转移公式不好找,有几点是DP法共有的,可以有点启发:1、DP大都借助数组实现递推操作 2、DP法的时间复杂度:一维为O(N),二维: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-1, j - 1] if A[i] == B[j]
4. d[i, j] = min(d[i-1, j - 1], d[i, j - 1], d[i-1, 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-1] == word2[j-1]) f[i][j] = f[i-1][j-1]; f[i][j] = min(f[i][j], f[i-1][j-1] + 1); //replace f[i][j] = min(f[i][j], min(f[i-1][j], f[i][j-1]) + 1); //delete or insert } return f[word1.size()][word2.size()]; } };
原文地址:http://blog.csdn.net/hustyangju/article/details/44955255