第43题 Edit Distance
来源:互联网 发布:钢铁力量数据 编辑:程序博客网 时间:2024/06/06 04:22
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
Solution in Java:
public class Solution { public int minDistance(String word1, String word2) { //opj[i][j] represents the steps to convert word1[0...i-1] to word2[0...j-1] //3 operations: // 1. insert a character: opj[i][j]=opj[i][j-1]+1 // exp: "abc" to "abca" insert an "a" to the end of "abc", then only need to match // "abc" with "abc", which is from i to j-1 // 2. delete a character: opj[i][j]=opj[i-1][j]+1 // exp: "abc" to "abca" delete a "b" from the end of "abc", then only need to match // "ab" with "abca", which is from i-1 to j // 3. Replace a character: opj[i-1][j-1] = opj[i-2][j-2]+ (word1[i-1]==word2[j-1])?0:1 // exp: "abc" to "abca" replace the last of "abc" with "a", then only need to match // "ab" with "abc", which is from i-1 to j-1 // exp: "abc" to "abcc" only need to match "ab" with "abc" from i-1 to j-1 and there is // no need to replace the last "c" of "abc" if(word1.length()==0||word2.length()==0) return Math.max(word1.length(), word2.length()); int len1 = word1.length(), len2 = word2.length(); int[][] opj = new int[len1+1][len2+1]; for(int i=0; i<=len1; i++){ //from word1[0...i-1] to "", need to delete i characters opj[i][0] = i; } for(int j=1; j<=len2; j++){ //from "" to word2[0...j-1], need to insert j characters opj[0][j] = j; } for(int i=1; i<=len1; i++){ for(int j=1; j<=len2; j++){ opj[i][j] = Math.min(opj[i][j-1]+1, opj[i-1][j]+1); opj[i][j] = Math.min(opj[i][j], opj[i-1][j-1]+(word1.charAt(i-1)==word2.charAt(j-1)?0:1)); } } return opj[len1][len2]; }}
0 0
- 第43题 Edit Distance
- 【leetcode】第72题 Edit Distance 题目+解析+JAVA代码
- edit distance
- Edit Distance
- edit distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- unity3D学习之Mono Develop脚本编辑器和常用核心类
- ubuntu下搭建tftp服务器
- Java相关知识一览
- unity3d
- git push.default设置
- 第43题 Edit Distance
- Linux下文件描述符(一)
- PHP设计模式——解释器模式
- 关于标签栏隐藏和显示的问题
- 判断当前fragment是否可见
- JQuery基础
- oracle实现累加,累计百分比计算
- 使用C++将OpenCV中Mat的数据写入二进制文件,用Matlab读出
- Windows静态库和动态库的创建和使用【转】