dynamicProgramming7

题目描述[原题链接][https://leetcode-cn.com/problems/edit-distance/]

给定两个单词 word1word2*,计算出将 *word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

  1. 插入一个字符
  2. 删除一个字符
  3. 替换一个字符

示例 1:

1
2
3
4
5
6
输入: word1 = "horse", word2 = "ros"
输出: 3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')

示例 2:

1
2
3
4
5
6
7
8
输入: word1 = "intention", word2 = "execution"
输出: 5
解释:
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

算法描述

。。。。。

C++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.size(), m = word2.size();
if(!n||!m)return m+n;
vector<vector<int>> f =
vector<vector<int>>(n+1,vector<int>(m+1));
f[0][0] = 0;
for(int i=1;i<=n;i++)f[i][0] = i;
for(int j=1;j<=m;j++)f[0][j] = j;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
f[i][j] = f[i-1][j-1]+
(word1[i-1]!=word2[j-1]);
f[i][j] = min(f[i][j],f[i-1][j]+1);
f[i][j] = min(f[i][j],f[i][j-1]+1);
}
}
return f[n][m];
}
};

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int minDistance(String word1, String word2) {
int n = word1.length(),m = word2.length();
if(n==0||m==0)return m+n;
int[][] f = new int[n+1][m+1];
f[0][0] = 0;
for(int i=1;i<=n;i++)f[i][0] = i;
for(int j=1;j<=m;j++)f[0][j] = j;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
int t = 0;
if(word1.charAt(i-1)!=word2.charAt(j-1))t=1;
f[i][j] = f[i-1][j-1]+t;
f[i][j] = Math.min(f[i][j],f[i-1][j]+1);
f[i][j] = Math.min(f[i][j],f[i][j-1]+1);
}
}
return f[n][m];

}
}