Edit Distance (LeetCode)

来源:互联网 发布:js超出部分省略号 编辑:程序博客网 时间:2024/06/03 03:36

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

做题之前看了一下Intro to Algorithm上的例题LCS,那题书上采用的是二维数组的dp,同理可推得这道题。

两个string S1, S2,path[i][j]记录的是S1(0,1,2...i)到S2(0,1,2...j)转换所需的步骤。

假设现在在S1的i位置,S2的j位置,那么一共有两种情况:

1. S1.charAt(i) == S2.charAt(j) 此时这一步不需要任何操作,path[i][j]==path[i-1][j-1];

2. S1.charAt(i) != S2.charAt(j) 这种情况下有三个选择

    a. 在s2中插入一个char which equals to S1(i),此时, path[i][j]= 1+path[i-1][j];

    b. 删除S2(j),然后比较S1(i)和S2(j-1),此时,path[i][j]=1+path[i][j-1];

    c. 将S2(j)替换为S1(i),此时,path[i][j]=1+path[i-1][j-1];

base case: path[0][i]=i (i from 1 : s1.length)   path[j][0]=j (j from 1 : s2.length)

public int minDistance(String word1, String word2) {        int[][] path = new int[word1.length()+1][word2.length()+1];        for(int i=0; i<path.length;i++)            path[i][0]=i;        for(int j=0;j<path[0].length;j++)            path[0][j]=j;                for(int i=1;i<=word1.length();i++){            for(int j=1;j<=word2.length();j++){                if(word1.charAt(i-1)==word2.charAt(j-1))                    path[i][j]=path[i-1][j-1];                else{                    path[i][j]=Math.min(path[i-1][j],path[i][j-1])+1;                    path[i][j]=Math.min(path[i][j],path[i-1][j-1]+1);                }            }        }        return path[word1.length()][word2.length()];    }


0 0
原创粉丝点击