当前位置:网站首页>Leetcode72. 编辑距离
Leetcode72. 编辑距离
2022-08-01 17:54:00 【Java全栈研发大联盟】
题目传送地址:https://leetcode.cn/problems/edit-distance/
运行效率:
解题思路
二维数组,动态规划法。 以后凡是看到两个对象匹配的题,首先想到二维数组,动态规划的办法。
代码如下:
class Solution {
public static int minDistance(String word1, String word2) {
//处理边界条件
if("".equals(word1)){
return word2.length();
}
if("".equals(word2)){
return word1.length();
}
//二维数组动态规划法
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;
}
}
//初始化第一列的数据
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;
}
}
//然后再依次填充其他
for (int row = 1; row < word2.length(); row++) {
for (int col = 1; col < word1.length(); col++) {
int leftObliqueVal = dp[row - 1][col - 1]; //左斜方的值
char cc1 = word1.charAt(col);
char cc2 = word2.charAt(row);
if (cc1 == cc2) {
dp[row][col] = leftObliqueVal;
} else {
int leftVal = dp[row][col-1]; //正左边的值
int topVal = dp[row - 1][col];//正上方的值
dp[row][col] = Math.min(Math.min(leftObliqueVal, leftVal), topVal) + 1;
}
}
}
return dp[word2.length() - 1][word1.length()-1];
}
}
边栏推荐
- 基于ORB-SLAM2的改进代码
- 变量交换;复合赋值;增递减运算符
- QPalette palette, frame color fill
- How can become a good architect necessary skills: painting for all the people praise the system architecture diagram?What is the secret?Quick to open this article and have a look!.
- ROS2系列知识(5):【参数】如何管理?
- SQL函数 TO_CHAR(三)
- 极化微波成像概述3
- Shell nl命令详解(显示行号、读取文件)
- B005 – 基于STC8的单片机智能路灯控制系统
- 吴恩达机器学习课后习题——kmeans
猜你喜欢
随机推荐
统信软件、龙芯中科等四家企业共同发布《数字办公安全创新方案》
EpiSci | Deep Reinforcement Learning for SoCs: Myth and Reality
8月微软技术课程,欢迎参与
B002 - 基于嵌入式的老人定位追踪监测仪
解决MySQL插入不了中文数据问题
插入排序 优化插入排序
golang json 返回空值
QT_事件类
sql添加索引
【100个网络运维工作者必须知道的小知识!】
【R语言】对图片进行裁剪 图片批量裁剪
星途一直缺颠覆性产品?青岛工厂这款M38T,会是个突破点?
素域和扩域
MySQL 慢查询
QT_QThread thread
极化微波成像概述3
SQL的substring_index()用法——MySQL字符串截取
主流小程序框架性能分析
【Day_10 0428】井字棋
基于BiGRU和GAN的数据生成方法