题目:
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 characterb) Delete a character
c) Replace a character
题解:
DP时创建横竖各多一行(列)的二维矩阵。
C++版:
class Solution {
public:
int minDistance(string word1, string word2) {
if (word1.length() == 0 && word2.length() == 0)
return 0;
if (word1.length() == 0)
return word2.length();
if (word2.length() == 0)
return word1.length();
vector<vector<int>> step;
for (int i = 0; i <= word1.length(); i++) {
vector<int> row(word2.length() + 1);
step.push_back(row);
}
step[0][0] = 0;
for (int i = 1; i <= word2.length(); i++) {
step[0][i] = i;
}
for (int j = 1; j <= word1.length(); j++) {
step[j][0] = j;
}
for (int m = 1; m <= word1.length(); m++) {
for (int n = 1; n <= word2.length(); n++) {
if (word1[m-1] == word2[n-1]) {
step[m][n] = step[m - 1][n - 1];
}
else {
step[m][n] = min(step[m - 1][n - 1], min(step[m - 1][n], step[m][n - 1])) + 1;
}
}
}
return step[word1.length()][word2.length()];
}
};
Java版:
public class Solution {
public int minDistance(String word1, String word2) {
if(word1.length() == 0 && word2.length() == 0)
return 0;
if(word1.length() == 0)
return word2.length();
if(word2.length() == 0)
return word1.length();
int[][] step = new int[word1.length()+1][word2.length()+1];
step[0][0] = 0;
for(int i = 1; i <= word2.length(); i++) {
step[0][i] = i;
}
for(int j = 1; j <= word1.length(); j++) {
step[j][0] = j;
}
for(int i = 1; i <= word1.length(); i++) {
for(int j = 1; j <= word2.length(); j++) {
if(word1.charAt(i-1) == word2.charAt(j-1))
step[i][j] = step[i-1][j-1];
else {
step[i][j] = Math.min(step[i-1][j-1], Math.min(step[i-1][j], step[i][j-1])) + 1;
}
}
}
return step[word1.length()][word2.length()];
}
}
Python版:
class Solution:
# @param {string} word1
# @param {string} word2
# @return {integer}
def minDistance(self, word1, word2):
if len(word1) == 0 and len(word2) == 0:
return 0
if len(word1) == 0:
return len(word2)
if len(word2) == 0:
return len(word1)
step = []
for i in range(len(word1)+1):
if i == 0:
c = [j for j in range(len(word2)+1)]
step.append(c)
else:
c = [i]
c = c + [0] * len(word2)
step.append(c)
for i in range(1, len(word1)+1):
for j in range(1, len(word2)+1):
if word1[i-1] == word2[j-1]:
step[i][j] = step[i-1][j-1]
else:
step[i][j] = min(step[i-1][j-1], min(step[i][j-1], step[i-1][j])) + 1
return step[len(word1)][len(word2)]