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
[Analysis]
经典问题,啥都不说,看例子慢慢领会。
array = [
s e a
0 1 2 3
e 1 1 1 2
a 2 2 2 1
t 3 3 3 2
]
return[n][n]
方法:先初始化加黑部分,然后
array[i][j] = (word1[i] == word2[j]) ? array[i-1][j-1] : min(array[i-1][j-1]+1, array[i-1][j]+1, array[i][j-1]+1)
[Solution]
class Solution {
public:// minimal element
int min(int a, int b, int c){
int tmp = (a < b ? a : b);
return tmp < c ? tmp : c;
}
// minimal distance
int minDistance(string word1, string word2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len1 = word1.length();
int len2 = word2.length();
// one of the word is empty
if(len1*len2 == 0){
return len1 + len2;
}
// both of them are not empty
int array[len1][len2];
for(int i = 0; i < word1.length(); ++i){
for(int j = 0; j < word2.length(); ++j){
int a, b, c;
// left upper one
if(i == 0 && j == 0){
a = 0;
}
else if(i == 0){
a = j;
}
else if(j == 0){
a = i;
}
else{
a = array[i-1][j-1];
}
// upper one
if(i == 0){
b = j+1;
}
else{
b = array[i-1][j];
}
// left one
if(j == 0){
c = i+1;
}
else{
c = array[i][j-1];
}
// update
if(word1[i] == word2[j]){
array[i][j] = a;
}
else{
array[i][j] = min(a+1, b+1, c+1);
}
}
}
return array[len1-1][len2-1];
}
};
说明:版权所有,转载请注明出处。 Coder007的博客