[LeetCode] Edit Distance

[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

[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的博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值