【LeetCode】72.Edit Distance解题报告
来源:互联网 发布:mac优酷 编辑:程序博客网 时间:2024/06/04 20:01
【LeetCode】72.Edit Distance解题报告
tags: DP String
题目地址:https://leetcode.com/problems/edit-distance/description/
题目描述:
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:
a) Insert a characterb) Delete a characterc) Replace a character
Solutions:
class Solution { public int minDistance(String word1, String word2) { int[][] dp = new int[word1.length()+1][word2.length()+1]; for(int i = 0; i <= word1.length() ; i++){ dp[i][0] = i; } for(int i = 0; i<=word2.length() ; i++){ dp[0][i] = i; } 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] = dp[i-1][j-1] + 1; //replace operation } dp[i][j] = Math.min(dp[i][j],Math.min(dp[i][j-1]+1,dp[i-1][j]+1)); } } return dp[word1.length()][word2.length()]; }}
此类String问题,有一个可用的模板。如下:
two conditions满足dp的两个条件1.optimal substructure最优子结构2.overlap subproblems重复子问题1->2: 0->1 replace 0->2 remove 1->1 insertdp[i][j]:min steps to convert word1 to word2 with length jthree steps:1.base case2.update function3.goala->b:""->b + removea -> "" +insertdp[i][j]dp[i-1][j-1]:previous operationdp[i-1][j]dp[i][j-1]
Date:2017年10月22日
阅读全文
0 0
- [leetcode] 72. Edit Distance 解题报告
- [Leetcode] 72. Edit Distance 解题报告
- 【LeetCode】72.Edit Distance解题报告
- [LeetCode] Edit Distance 解题报告
- Edit Distance [Leetcode解题报告]
- Leetcode 72. Edit Distance 编辑距离 解题报告
- [leetcode] One Edit Distance 解题报告
- [Leetcode] 161. One Edit Distance 解题报告
- Edit Distance 解题报告
- LeetCode 72. Edit Distance
- [LeetCode]72.Edit Distance
- LeetCode --- 72. Edit Distance
- [Leetcode] 72. Edit Distance
- [leetcode] 72.Edit Distance
- [leetcode] 72.Edit Distance
- Leetcode 72. Edit Distance
- LeetCode 72. Edit Distance
- leetcode 72. Edit Distance
- Windows下NTFS连接点管理工具-junction工具说明
- gradle 知识(1) -- gradle构建工具
- 小朋友学C语言(14):分苹果(小学奥数题)
- 树莓派设置固定IP
- 图像二值化
- 【LeetCode】72.Edit Distance解题报告
- Arrays用法整理
- 怎么在VirtualBox上装电脑公司的win7系统
- 实时调试WebDriver代码
- 小朋友学C语言(15):“变量==常量”与“常量==变量”的区别
- week_5_ Integer to Roman
- 完整代码示例
- Error: Could not link: /usr/local/share/doc/homebrew
- nginx安装配置