72. Edit Distance
来源:互联网 发布:烟台关键词优化报价 编辑:程序博客网 时间:2024/06/18 17:21
原题:
Given two words word1 and word2, find the minimum number of steps required to convertword1 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
即输入两个字符串,返回由其中一个字符串转化成另一个字符串的最少步数(只能通过插入字符、删除字符和替换字符的操作)。
解题思路:
这道题是用动态规划思路解的:用D(L1,L2)表示第一个字符串L1长度转化为第二个字符串L2长度最少步数。那就有关系:
D(L1,L2) = min{D(L1-1,L2)+1,D(L1,L2-1)+1,D(L1-1,L2-1) + s1.charAt(L1 -1) == s2.charAt(L2 - 1)? 0:1}
min里面的三个元素分别表示s1删除一个字符、插入一个字符和替换一个字符的操作。
AC代码:
int[][] matrix; String word1,word2; public int minDistance(String word1, String word2) { this.word1 = word1; this.word2 = word2; int len1 = word1.length(),len2 = word2.length(); matrix = new int[len1+1][len2+1]; if (len1 == 0) return len2; if (len2 == 0) return len1; //下面初始化时步数多加了1,是为了以后根据矩阵元素是否为0就可以判断此元素是否计算过。最后返回结果时记得减一就可以了 matrix[0][0] = 1; /*if (len1 == 1) return matrix[0][0] + len2 - len1;//控制某个字符串只有一个字符的情况,防止下面越界 if (len2 == 1) return matrix[0][0] + len1 - len2; matrix[0][1] = matrix[0][0] + 1; matrix[1][0] = matrix[0][0] + 1;*/ return findEditDistance(len1,len2) - 1; } /* 寻找word1前i+1个字符合word2前j+1个字符匹配最小步数 */ public int findEditDistance(int i,int j){ if (matrix[i][j] != 0) return matrix[i][j]; int r1 = Integer.MAX_VALUE,r2 = Integer.MAX_VALUE,r3 = Integer.MAX_VALUE; boolean b1 = i > 0,b2 = j > 0,b3 = b1 && b2; if (b1) r1 = findEditDistance(i - 1,j) + 1; if (b2) r2 = findEditDistance(i,j - 1) + 1; if (b3) r3 = findEditDistance(i-1,j-1) + (word1.charAt(i-1) == word2.charAt(j-1)? 0:1); matrix[i][j] = Math.min(r1,Math.min(r2,r3)); return matrix[i][j]; }
阅读全文
1 0
- LeetCode 72. Edit Distance
- [LeetCode]72.Edit Distance
- LeetCode --- 72. Edit Distance
- [Leetcode] 72. Edit Distance
- [leetcode] 72.Edit Distance
- 72. Edit Distance
- [leetcode] 72.Edit Distance
- 72. Edit Distance
- Leetcode 72. Edit Distance
- 72. Edit Distance
- LeetCode 72. Edit Distance
- leetcode 72. Edit Distance
- LeetCode 72. Edit Distance
- Leetcode 72. Edit Distance
- 72. Edit Distance
- Leetcode:72. Edit Distance
- 【LeetCode】72. Edit Distance
- leetCode 72. Edit Distance
- Java快速排序
- java 图形用户界面
- WPF与MVVM的实现(二)数据绑定
- Android Studio自带的多渠道打包简单使用
- Machine Schedule
- 72. Edit Distance
- angularjs ng-if表达式为true的情况下标签仍不显示内容
- 微信公众号开发入门
- PhantomJS安装过程中遇到的问题
- 字符遊戲--貪吃蛇(智能)
- 用日志了解你的 Linux 系统
- coursera Machine Learning 第八周 测验quiz2答案解析 Principal Component Analysis
- Loading transformation from repository [addSyncDate] in directory [/] [Fatal Error]
- 莫比乌斯反演入门