当前位置:网站首页>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];
}
}
边栏推荐
猜你喜欢
随机推荐
tooltip 控件
typora操作手册
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践
【Day_10 0428】密码强度等级
MySQL 45 讲 | 09 普通索引和唯一索引,应该怎么选择?
Review实战经典:2 种封装风格,你偏爱哪种?
EpiSci | Deep Reinforcement Learning for SoCs: Myth and Reality
RecSys'22|CARCA: Cross-Attention-Aware Context and Attribute Recommendations
QPalette调色板、框架色彩填充
GRUB2的零日漏洞补丁现已推出
golang json 返回空值
B011 - 51-based multifunctional fingerprint smart lock
B011 - 基于51的多功能指纹智能锁
Basic image processing in opencv
Are online account opening commissions reliable? Is online account opening safe?
MySQL 慢查询
数字化采购管理系统开发:精细化采购业务流程管理,赋能企业实现“阳光采购”
主流小程序框架性能分析
成为优秀架构师必备技能:怎样才能画出让所有人赞不绝口的系统架构图?秘诀是什么?快来打开这篇文章看看吧!...
粒子滤波 particle filter —从贝叶斯滤波到粒子滤波——Part-I(贝叶斯滤波)









