第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

Hide Tags
 Dynamic Programming String










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
原创粉丝点击