标签:动态规划

描述:

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

  • Insert a character
  • Delete a character
  • Replace a character

解题思路:

这一题做的很快,与之前的字符串匹配问题一样,在word1与word2的两个向量上分解字符串,同时遍历两个字符串:分别在两个子串中进行比较,

对于子串中拥有相同的字符的情况下:加入这个字符与不加入这个字符的意义是相同的,不会有更多的变化,所以有公式:

dp[i][j] = dp[i-1][j-1]

当两个子串的匹配的字符不同的情况下:有三种情况可以达到当前状态,修改1位,删除1位,加入1位,三个分别的位置为dp[i-1][j], dp[i][j-1],dp[i-1][j-1]

且三个位置记录着之前状态下,所存在的最小变化情况。所以要在当前状态下达到最小,则需要在之前最小的情况下加上1,所以公式有:

dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])+1

参考代码:

 public int minDistance(String word1, String word2) {
// write your code here
int[][] dp = new int[word1.length()+1][word2.length()+1]; for(int i = 0; i<=word1.length(); i++){
dp[i][0] = i;
} for(int j = 0; j<=word2.length(); j++){
dp[0][j] = j;
} for(int i=1; i<= word1.length(); i++){
for(int j=1; j<=word2.length(); j++){
if(word1.charAt(i-1)==word2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1]))+1;
}
}
} return dp[word1.length()][word2.length()]; }

最新文章

  1. bzoj4025 二分图
  2. 深入理解javascript原型和闭包(17)——补this
  3. js实现图片无缝连接
  4. C# 统计程序执行时间
  5. Nginx实现静态资源的缓存
  6. webim-界面细节调整
  7. [topcoder]AvoidRoads
  8. Android的string-array数据源简单使用
  9. [React] React Fundamentals: Component Lifecycle - Mounting Basics
  10. oracle包概述(一)【weber出品】
  11. 教务处sso设计缺陷
  12. Mixin模式:带实现的协议
  13. Docker aufs存储驱动layer、diff、mnt目录的区别
  14. C#的Random到底该怎么使用
  15. 使用idea搭建maven项目
  16. IDEA 启动项目前的配置--或过程遇到的问题
  17. CSDN沙龙记录
  18. 字符串匹配的 KMP算法
  19. 解决在使用pip list时出现DEPRECATION
  20. 使用NATS替换NSQ为后台服务解耦

热门文章

  1. java生成excel报表文件
  2. Python学习day06-Python基础(4)流程控制之while和for循环
  3. Referenced assembly does not have a strong name
  4. HtmlHelper2
  5. Chapter 3 树与二叉树
  6. CSS 的overflow:hidden (清除浮动)
  7. 深度神经网络Google Inception Net-V3结构图
  8. golang Linux下编译环境搭建
  9. cannot be cast to javax.servlet.Servlet 解决
  10. HZOI20190906模拟38 金,斯诺,赤