当前位置:网站首页>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];
}
}
边栏推荐
- 百度网盘下载速度提升100倍
- 关于Mysql服务无法启动的问题
- When custom annotations implement log printing, specific fields are blocked from printing
- SQL的ROUND函数用法及其实例
- 理财产品的月年化收益率怎么算?
- Xingtu has been short of disruptive products?Will this M38T from the Qingdao factory be a breakthrough?
- opencv基本的图像处理
- 棕榈油罐区数字化转型
- TCP million concurrent server optimization parameters
- EpiSci | Deep Reinforcement Learning for SoCs: Myth and Reality
猜你喜欢

B005 – 基于STC8的单片机智能路灯控制系统

ROS2支持技术:DDS简述

C language theory--a solid foundation for the written test and interview

zabbix部署和简单使用

XAML WPF item groupBox control

MySQL 45 Talk | 09 How to choose common index and unique index?

晶振工作原理详解

Unity ui点击事件只响应最上层ui的方式
OnePlus 10RT appears on Geekbench, product launch also seems to be approaching

The anxiety of the post-90s was cured by the vegetable market
随机推荐
opencv基本的图像处理
浅谈大数据背景下数据库安全保障体系
C语言:表达式求值详解
不需要写代码,快速批量修改文件夹中图片的格式
TCP million concurrent server optimization parameters
打开微信客服
关系运算符和if,else语句
千万级乘客排队系统重构&压测方案总结篇
半自动化爬虫-爬取一个网站的内容及回复
【Day_11 0506】 最近公共祖先
Solve the problem that MySQL cannot insert Chinese data
【Day_10 0428】井字棋
自定义注解实现日志打印时屏蔽特定字段不打印
QT_事件类
【100个网络运维工作者必须知道的小知识!】
tooltip 控件
【R语言】批量重命名文件
OnePlus 10RT appears on Geekbench, product launch also seems to be approaching
Shell nl命令详解(显示行号、读取文件)
想做期货,农产品期货怎么炒?波动大么