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

QT基础功能,信号、槽

B001 - Intelligent ecological fish tank based on STM32

Shell nl命令详解(显示行号、读取文件)

TCP million concurrent server optimization parameters
OnePlus 10RT appears on Geekbench, product launch also seems to be approaching

计算IoU(D2L)

B002 - Embedded Elderly Positioning Tracking Monitor

Topology零部件拆解3D可视化解决方案

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

QLineEdit学习与使用
随机推荐
【Day_12 0507】二进制插入
opencv语法Mat类型总结
LeaRun.net快速开发动态表单
深入分析类加载器
Basic image processing in opencv
C语言理论--笔试面试基础稳固
QT_QThread thread
【报错】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat‘)
SQL函数 TO_CHAR(一)
计算IoU(D2L)
2022.08月--pushmall推贴共享电商更新与开发计划
MySQL 45 Talk | 09 How to choose common index and unique index?
OpenCV安装、QT、VS配置项目设置
Topology Parts Disassembly 3D Visualization Solution
TCP百万并发服务器优化调参
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) Solution
极化微波成像概述
QT commonly used global macro definitions
【R语言】线性混合模型进行重复测量设计分析
小贝拉机器人是朋友_普渡科技召开新品发布会,新一代送餐机器人“贝拉”温暖登场...