LeetCode 72. Edit Distance(编辑距离)
2016-05-22 05:18
405 查看
原题网址:https://leetcode.com/problems/edit-distance/
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 character
b) Delete a character
c) Replace a character
方法一:动态规划。
方法二:动态规划,优化内存。
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 character
b) Delete a character
c) Replace a character
方法一:动态规划。
public class Solution { public int minDistance(String word1, String word2) { char[] wa1 = word1.toCharArray(); char[] wa2 = word2.toCharArray(); int[][] distance = new int[wa1.length+1][wa2.length+1]; for(int len2=1; len2<=wa2.length; len2++) distance[0][len2] = len2; for(int len1=1; len1<=wa1.length; len1++) { distance[len1][0] = len1; for(int len2=1; len2<=wa2.length; len2++) { if (wa2[len2-1] == wa1[len1-1]) distance[len1][len2] = distance[len1-1][len2-1]; else distance[len1][len2] = Math.min(distance[len1-1][len2-1], Math.min(distance[len1][len2-1], distance[len1-1][len2])) + 1; } } return distance[wa1.length][wa2.length]; } }
方法二:动态规划,优化内存。
public class Solution { public int minDistance(String word1, String word2) { char[] wa1 = word1.toCharArray(); char[] wa2 = word2.toCharArray(); int[] distance = new int[wa2.length+1]; int[] buf = new int[wa2.length+1]; for(int len2=0; len2<=wa2.length; len2++) distance[len2] = len2; for(int len1=1; len1<=wa1.length; len1++) { int[] prev = distance; distance = buf; distance[0] = len1; for(int len2=1; len2<=wa2.length; len2++) { if (wa1[len1-1] == wa2[len2-1]) distance[len2] = prev[len2-1]; else distance[len2] = Math.min(prev[len2-1], Math.min(distance[len2-1], prev[len2])) + 1; } buf = prev; } return distance[wa2.length]; } }
相关文章推荐
- LeetCode 73. Set Matrix Zeroes(矩阵清零)
- 输入输出外挂总结
- leetcode #22 in cpp
- 关于Gson.jar导入正常使用,代码无错,但程序执行解析时崩溃的一些问题
- [PWA] 18. Clean the photo cache
- leetcode #21 in cpp
- mathematica试除法解素数问题
- 全局eval的实现
- 法国劳动法案引大罢工 一场“无解”的左翼运动
- [PWA] 17. Cache the photo
- Notepad++正则表达式中几点需要注意的地方
- python sorted
- 303. Range Sum Query - Immutable
- notepad++正则匹配及匹配内容的保留与处理
- 浅谈多线程中GCD(有图有真相) iOS中如何实现多线程同步
- 框架 day33 Hibernate,组件映射,继承映射,抓取(检索)策略-优化,检索方式总结
- 实战SSH端口转发
- equal_range用法
- [leetcode] 【数组】27. Remove Element
- 明明将gson-2.3.1.jar 包复制粘贴在所在工程libs目录下,却无法使用