编辑距离
- https://leetcode.cn/problems/edit-distance/description/
描述
- 给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所利用的最少操作数
- 你可以对一个单词进行如下三种操作:
示例 1
- 输入:word1 = "horse", word2 = "ros"
- 输出:3
复制代码 解释:
horse -> rorse (将 ‘h’ 替换为 ‘r’)
rorse -> rose (删除 ‘r’)
rose -> ros (删除 ‘e’)
示例 2
- 输入:word1 = "intention", word2 = "execution"
- 输出:5
复制代码 解释:
intention -> inention (删除 ‘t’)
inention -> enention (将 ‘i’ 替换为 ‘e’)
enention -> exention (将 ‘n’ 替换为 ‘x’)
exention -> exection (将 ‘n’ 替换为 ‘c’)
exection -> execution (插入 ‘u’)
提示
- 0 <= word1.length, word2.length <= 500
- word1 和 word2 由小写英文字母组成
Typescript 版算法实现
1 ) 方案1: 动态规划
- function minDistance(word1: string, word2: string): number {
- const n = word1.length;
- const m = word2.length;
- // 有一个字符串为空串
- if (n * m === 0) {
- return n + m;
- }
- // DP 数组
- const D: number[][] = Array.from({ length: n + 1 }, () => Array(m + 1).fill(0));
- // 边界状态初始化
- for (let i = 0; i < n + 1; i++) {
- D[i][0] = i;
- }
- for (let j = 0; j < m + 1; j++) {
- D[0][j] = j;
- }
- // 计算所有 DP 值
- for (let i = 1; i < n + 1; i++) {
- for (let j = 1; j < m + 1; j++) {
- const left = D[i - 1][j] + 1;
- const down = D[i][j - 1] + 1;
- let left_down = D[i - 1][j - 1];
- if (word1.charAt(i - 1) !== word2.charAt(j - 1)) {
- left_down += 1;
- }
- D[i][j] = Math.min(left, down, left_down);
- }
- }
- return D[n][m];
- }
复制代码 2 ) 方案2: 动态规划自底向上
- function minDistance(word1: string, word2: string): number {
- const n1 = word1.length;
- const n2 = word2.length;
- // 初始化 DP 数组
- const dp: number[][] = Array.from({ length: n1 + 1 }, () => Array(n2 + 1).fill(0));
- // 初始化第一行
- for (let j = 1; j <= n2; j++) {
- dp[0][j] = dp[0][j - 1] + 1;
- }
- // 初始化第一列
- for (let i = 1; i <= n1; i++) {
- dp[i][0] = dp[i - 1][0] + 1;
- }
- // 计算所有 DP 值
- for (let i = 1; i <= n1; i++) {
- for (let j = 1; j <= n2; j++) {
- if (word1.charAt(i - 1) === word2.charAt(j - 1)) {
- dp[i][j] = dp[i - 1][j - 1];
- } else {
- dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1;
- }
- }
- }
- return dp[n1][n2];
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |