【1】【leetcode-72 动态规划】 编辑距离
2024-10-12 10:00:51
(没思路,很典型,重要)
给定两个单词 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')
关键:
dp[i][j]代表由word1的前i个子串变为word2的前j个子串的花费
在删除,插入,修改中取花费最小的那个:dp[i][j] = Math.min(Math.min(dp[i-
1
][j], dp[i][j-
1
]), dp[i-
1
][j-
1
]) +
1
;
链接:https://www.nowcoder.com/questionTerminal/81d7738f954242e5ade5e65ec40e5027
来源:牛客网 public class Solution {
public int minDistance(String word1, String word2) {
if(word1 == null && word2 == null)
return 0;
if(word1 == null)
return word2.length();
if(word2 == null)
return word1.length();
// dp[i][j]代表由word1的前i个子串变为word2的前j个子串的花费
// 其中i,j均可为0,代表空串:""
int[][] dp = new int[word1.length() + 1][word2.length() + 2];
dp[0][0] = 0;
// 首先初始化两个子串中有一个为空串的情况
for(int i = 1; i <= word1.length(); i++){
dp[i][0] = i;
}
for(int j = 1; j <= word2.length(); j++){
dp[0][j] = j;
}
for(int i = 1; i <= word1.length(); i++){
for(int j = 1; j <= word2.length(); j++){
// 如果这两个字符相等,那么交由上一种情况处理,如abc,dfc
// 这种情况与ab,df花费是一样的
// 不然就要在删除,插入,修改中取花费最小的那个
if(word1.charAt(i - 1) == word2.charAt(j - 1))
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
}
}
return dp[word1.length()][word2.length()];
}
}
我:
public int minDistance(String word1, String word2) {
int length1 = word1.length();
int length2 = word2.length(); int[][] dp = new int[length1+1][length2+1];
for (int i=0;i<=length1;i++) {
dp[i][0] = i;
}
for (int i=0;i<=length2;i++) {
dp[0][i] = i;
}
for (int i=1;i<=length1;i++) {
for (int j=1;j<=length2;j++) {
if (word1.charAt(i-1) == word2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1];
} else {
dp[i][j] = 1 + Math.min(dp[i-1][j-1],Math.min(dp[i][j-1],dp[i-1][j]));
}
}
}
return dp[length1][length2];
}
最新文章
- MongoDB replica set IDs do not match
- SQL server 动态行转列
- php缓存技术总结
- 一些常用的html/CSS效果---小技巧
- Http请求中POST与GET的区别——前端面试
- 20145207 《Java程序设计》第一周学习总结
- PLSQL读取XML的数据
- shell 括号学习
- RichTextBox控件-主要用于输入输出编辑文本信息
- 工欲善其事必先利其器-Notepad++使用小记(Python)
- JVM基础和调优(五)
- 《学习记录》ng2-bootstrap中的component使用教程
- Leetcode_102_Binary Tree Level Order Traversal
- centos 7查看防火墙报错(已解决,之前安装过python3)
- jwt、session、oauth 异同
- java的坦克大战
- commons-lang3工具类学习(二)
- bootstrap 模态框事件
- msp430学习笔记-USART
- java内部类作用