72. 编辑距离

给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

插入一个字符

删除一个字符

替换一个字符

示例 1:

输入: word1 = “horse”, word2 = “ros”

输出: 3

解释:

horse -> rorse (将 ‘h’ 替换为 ‘r’)

rorse -> rose (删除 ‘r’)

rose -> ros (删除 ‘e’)

示例 2:

输入: word1 = “intention”, word2 = “execution”

输出: 5

解释:

intention -> inention (删除 ‘t’)

inention -> enention (将 ‘i’ 替换为 ‘e’)

enention -> exention (将 ‘n’ 替换为 ‘x’)

exention -> exection (将 ‘n’ 替换为 ‘c’)

exection -> execution (插入 ‘u’)

class Solution {
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
//处理有空字符串的特殊情况
if (len1 * len2 == 0)
return len1 + len2;
String longerStr = len1 > len2 ? word1 : word2;
String shorterStr = len1 > len2 ? word2 : word1;
int shorterOne = Math.min(len1, len2);
//dp数组长度为两字符串中长度较小的那个
int[] dp = new int[shorterOne + 1];
//初始化dp数组
for (int i = 0; i < shorterOne + 1; i++) {
dp[i] = i;
}
//从长度较长的字符串开始遍历,注意j从1开始,取第j-1位字符,因此结束位置是 longerStr.length()
for (int j = 1; j <= longerStr.length(); j++) {
// 每次遍历短字符串前,先给left赋初始值
int left = j;
//遍历长度较短的字符串,同样从1开始,取第i-1位字符,因此结束位置是 shortStr.length()
for (int i = 1; i <= shorterStr.length(); i++) {
int updateDown = dp[i] + 1;
int updateLeft = left + 1;
int updateLeftDown = dp[i - 1];
//如果当前字符不匹配,左下角的那个值要加一,表示替换当前字符
if (longerStr.charAt(j - 1) != shorterStr.charAt(i - 1)) {
updateLeftDown++;
}
//获取较小的那个
int min = Math.min(updateLeft, Math.min(updateDown, updateLeftDown));
//因为 dp[i - 1]后面用不到了,替换为当前的left值
dp[i - 1] = left;
//如果遍历到最后一个时,直接更新dp[i]
if(i == dp.length - 1){
dp[i] = min;
}else{
//否则更新左边的值,而不是直接更新 dp[i],因为下个循环需要用到原来的 dp[i]以及刚更新的left
left = min;
}
}
}
return dp[shorterOne];
}
}

最新文章

  1. angularjs自带过滤器
  2. ios10 xcode8 适配的那些事
  3. Science上发表的超赞聚类算法
  4. python 发送邮件函数模块
  5. 【转】ViewPager实现一个页面多个Item的显示
  6. ClassLoader,Thread.currentThread().setContextClassLoader,tomcat的ClassLoader
  7. MongoDB 1: NoSQL 和 SQL的区别
  8. Jersey(1.19.1) - Hello World, Get started with Jersey using the embedded Grizzly server
  9. 【Linux安全】文件或目录权限设置
  10. arm 及ndk编译
  11. ng-select ng-options ng-repeat的用法与区别
  12. HTML5,微信开发原码社区
  13. MobileProbe的使用
  14. python executemany的使用
  15. 51 nod 1023 石子归并 V3(GarsiaWachs算法)
  16. 【Java】数组转List常见方式的对比
  17. 为什么Dotnet Core的DI默认是在控制器中注入
  18. Markdown语法说明(转)
  19. BootStrap学习(1)
  20. 服务容错保护断路器Hystrix之三:断路器监控(Hystrix Dashboard)-单体监控

热门文章

  1. linux磁盘已满,查看哪个文件占用多
  2. 【Django组件】KindEditor富文本编辑器上传文件,html样式文本,VUE异步提交数据(易懂版)
  3. 盲注fuzz
  4. JavaScript之ES5的继承
  5. OpenCv 学习安装(一)
  6. 使用naxsi
  7. 全网最详细最好懂 PyTorch CNN案例分析 识别手写数字
  8. 13.2 Go练习题答案
  9. Spring @Autowired 注释
  10. UIStackView上手教程