Leetcode: NO.72 编辑距离
2020-04-07 08:46
267 查看
题目
链接:https://leetcode-cn.com/problems/edit-distance
给你两个单词 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')
解题记录
通过动态规划求解,动态规划一般都是通过分解问题,从结果向前推断,本题中如果两个字符相同的话不需要操作,dp[i][j] = dp[i-1][j-1]
,如果不同的话,就是之前三种情况变更(+1)得到,既dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
,推到头,确定其实值为‘’,‘’字符串变成任何字符串需要的距离都是该字符串的长度。
class Solution { public static int minDistance(String word1, String word2) { char[] seq1 = word1.toCharArray(); char[] seq2 = word2.toCharArray(); int[][] dp = new int[seq1.length + 1][seq2.length + 1]; for (int i = 0; i <= seq1.length; i++) { for (int j = 0; j <= seq2.length; j++) { if (i==0) dp[i][j] = j; else if (j==0) dp[i][j] = i; else if (seq1[i - 1] == seq2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; else dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]) + 1; } } return dp[seq1.length][seq2.length]; } }
结果
相关文章推荐
- LeetCode-72. Edit Distance (JAVA)字符串最小编辑距离DP&DFS
- LeetCode72编辑距离
- [LeetCode] 72. Edit Distance 编辑距离
- leetcode:72. 最小编辑距离
- LeetCode | Edit Distance(字符串编辑距离)
- Leetcode 72. 编辑距离
- [LeetCode] 161. One Edit Distance 一个编辑距离
- 【leetcode】编辑距离
- [LeetCode] [动态规划] [编辑距离] Edit Distance
- leetCode 72.Edit Distance (编辑距离) 解题思路和方法
- LeetCode刷题 | 72. Edit Distance 难题 编辑距离dp
- LeetCode72. 编辑距离
- leetcode 72. Edit Distance 编辑距离(字符串动态规划)
- LeetCode之计算字符串相似度或编辑距离EditDistance
- leetcode 72:编辑距离
- leetcode 72. 编辑距离
- (Leetcode 72) 编辑距离
- LeetCode72. 编辑距离(动态规划)
- (LeetCode 72)编辑距离 [动态规划 + 字符串好题]
- LeetCode-161.One Edit Distance (JAVA)一次编辑距离