当前位置:网站首页>Leetcode72. Edit Distance
Leetcode72. Edit Distance
2022-08-01 17:59:00 【Java Full Stack R&D Alliance】
题目传送地址:https://leetcode.cn/problems/edit-distance/
运行效率:
解题思路
二维数组,动态规划法. In the future, I will always see a question where two objects match,Two-dimensional arrays come to mind first,动态规划的办法.
代码如下:
class Solution {
public static int minDistance(String word1, String word2) {
//处理边界条件
if("".equals(word1)){
return word2.length();
}
if("".equals(word2)){
return word1.length();
}
//Two-dimensional array dynamic programming method
int[][] dp = new int[word2.length()][word1.length()];
char c1 = word1.charAt(0);
char c2 = word2.charAt(0);
//初始化第一行的数据
for (int col = 0; col < word1.length(); col++) {
String substring = word1.substring(0, col + 1);
if (substring.indexOf(c2) != -1) {
dp[0][col] = col;
} else {
dp[0][col] = col+1;
}
}
//Initialize the first column of data
for (int row = 0; row < word2.length(); row++) {
String substring = word2.substring(0, row + 1);
if (substring.indexOf(c1) != -1) {
dp[row][0] = row;
} else {
dp[row][0] = row + 1;
}
}
//Then fill in the others in turn
for (int row = 1; row < word2.length(); row++) {
for (int col = 1; col < word1.length(); col++) {
int leftObliqueVal = dp[row - 1][col - 1]; //The value of the left slope
char cc1 = word1.charAt(col);
char cc2 = word2.charAt(row);
if (cc1 == cc2) {
dp[row][col] = leftObliqueVal;
} else {
int leftVal = dp[row][col-1]; //positive left value
int topVal = dp[row - 1][col];//value directly above
dp[row][col] = Math.min(Math.min(leftObliqueVal, leftVal), topVal) + 1;
}
}
}
return dp[word2.length() - 1][word1.length()-1];
}
}
边栏推荐
- 银行案例|Zabbix跨版本升级指南,4.2-6.0不香吗?
- C language theory--a solid foundation for the written test and interview
- 加州大学|通过图抽象从不同的第三人称视频中进行逆强化学习
- RecSys'22|CARCA: Cross-Attention-Aware Context and Attribute Recommendations
- XAML WPF item groupBox control
- 【100个网络运维工作者必须知道的小知识!】
- EpiSci|片上系统的深度强化学习:神话与现实
- 食品安全 | 新鲜食品vs速食食品,哪一种是你的菜?
- el-form-item prop属性动态绑定不生效如何解决
- ROS2系列知识(5):【参数】如何管理?
猜你喜欢
随机推荐
【Day_09 0427】 另类加法
不需要写代码,快速批量修改文件夹中图片的格式
AIOps智能运维的领跑者擎创科技正式入驻InfoQ 写作社区!
GTK修改pixmap像素,提取pixmap像素RGB值
Topology零部件拆解3D可视化解决方案
开发工具:第五章:使用idea生成实体类
C语言理论--笔试面试基础稳固
Solve the problem that MySQL cannot insert Chinese data
Review实战经典:2 种封装风格,你偏爱哪种?
QT_QDialog dialog
SRM供应商管理系统如何助力口腔护理企业实现采购战略的转型升级
ROS2系列知识(6):Action服务概念
变量交换;复合赋值;增递减运算符
理财产品的月年化收益率怎么算?
hcip第九天
md5sum源码 可多平台编译
Shell nl命令详解(显示行号、读取文件)
QT_QThread线程
MySQL 45 Talk | 09 How to choose common index and unique index?
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)