当前位置:网站首页>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];
}
}
边栏推荐
猜你喜欢

频域分析实践介绍

SRM供应商管理系统如何助力口腔护理企业实现采购战略的转型升级

B001 - Intelligent ecological fish tank based on STM32

基于BiGRU和GAN的数据生成方法

QT_QThread线程

后台管理系统的权限思路

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!.

M1芯片电脑安装cerebro

B001 - 基于STM32的智能生态鱼缸

以消费场景为驱动的CMDB要怎么建?
随机推荐
SQL的substring_index()用法——MySQL字符串截取
【Day_12 0507】二进制插入
三维空间中点的插值
hcip第九天
频域分析实践介绍
Shell nl命令详解(显示行号、读取文件)
打开微信客服
【TDP加码福利】COS用户实践征文月,等你来投稿!!!
B001 - Intelligent ecological fish tank based on STM32
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) Solution
bat 批示处理详解-2
Leetcode73. 矩阵置零
QLineEdit学习与使用
QT_QThread线程
不需要写代码,快速批量修改文件夹中图片的格式
2022年SQL大厂高频实战面试题(详细解析)
快速抽取resnet_v2_152中间的特征层
百度网盘下载速度提升100倍
成都理工大学&电子科技大学|用于强化学习的域自适应状态表示对齐
理财产品的月年化收益率怎么算?