Description
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Examples
Example 1:
Input: word1 = “horse”, word2 = “ros”
Output: 3
**Explanation: **
horse -> rorse (replace ‘h’ with ‘r’)
rorse -> rose (remove ‘r’)
rose -> ros (remove ‘e’)
Example 2:
Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)
解题思路
也可以算作是一个动态规划,里面的更新函数是
a
n
s
w
e
r
[
i
]
[
j
]
=
m
i
n
(
a
n
s
w
e
r
[
i
−
1
]
[
j
]
+
1
,
a
n
s
w
e
r
[
i
]
[
j
−
1
]
+
1
,
a
n
s
w
e
r
[
i
−
1
]
[
j
−
1
]
+
s
a
m
e
)
answer[i][j] = min(answer[i-1][j]+1, answer[i][j-1]+1, answer[i-1][j-1]+same)
answer[i][j]=min(answer[i−1][j]+1,answer[i][j−1]+1,answer[i−1][j−1]+same)
其中
s
a
m
e
same
same的值
s
a
m
e
=
1
,
w
o
r
d
1
[
i
]
!
=
w
o
r
d
2
[
j
]
same = 1, word1[i] != word2[j]
same=1,word1[i]!=word2[j]
s
a
m
e
=
0
,
w
o
r
d
1
[
i
]
=
=
w
o
r
d
2
[
j
]
same = 0, word1[i] == word2[j]
same=0,word1[i]==word2[j]
很明显
a
n
s
w
e
r
[
i
−
1
]
[
j
]
+
1
answer[i-1][j]+1
answer[i−1][j]+1表示插入操作,
a
n
s
w
e
r
[
i
]
[
j
−
1
]
+
1
answer[i][j-1]+1
answer[i][j−1]+1表示删除操作,
a
n
s
w
e
r
[
i
−
1
]
[
j
−
1
]
+
s
a
m
e
answer[i-1][j-1]+same
answer[i−1][j−1]+same表示替换操作
求
m
i
n
min
min表示三者相遇取其轻
当然这个方法不会是我自己想出来的……是从网上摸得orz
初始化就是
a
n
s
w
e
r
[
i
]
[
0
]
=
i
,
a
n
s
w
e
r
[
0
]
[
i
]
=
i
answer[i][0] = i, answer[0][i] = i
answer[i][0]=i,answer[0][i]=i,可以理解为一个word是空字符串,那另一个word就要不停进行插入操作对齐进行填充。
代码
class Solution {
public int min(int a, int b, int c){
if(a <= b && a <= c)
return a;
if(b <= a && b <= c)
return b;
if(c <= a && c <= b)
return c;
return a;
}
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
int[][] ans = new int[len1 + 1][len2 + 1];
int i, j;
for(i = 0; i < len1 + 1; i++){
ans[i][0] = i;
}
for(i = 0; i < len2 + 1; i++){
ans[0][i] = i;
}
for(i = 1; i < len1 + 1; i++){
for(j = 1; j < len2 + 1; j++){
int add = 1;
if(word1.charAt(i - 1) == word2.charAt(j - 1))
add = 0;
ans[i][j] = min(ans[i - 1][j] + 1, ans[i - 1][j - 1] + add, ans[i][j - 1] + 1);
}
}
return ans[len1][len2];
}
}