leetCode练习(72)

来源:互联网 发布:电脑什么软件跑分准 编辑:程序博客网 时间:2024/05/21 05:41

题目:Edit Distance

难度:hard

问题描述:

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

解题思路:这是一道经典的语言处理问题,叫做最短编辑距离。使用了动态规划的解法。题目中,我们可以使用增,删,改三种方式操作字符串word2,使之变成word1.求最少编辑次数。题目中增删改都算一次操作,经典问题中,改算为两次操作。这里需要注意。

我们使用数组D(i,j),表示word1的前I个字符和word2的前j个字符组成的子问题的最少编辑次数。显然,D(0,j)和D(i,0)分别为j和I。

然后,对于D(x,y),要么是D(x-1,y)的情况下,再增上word1【x】,要么是D(x,y-1)再减去word2【y】,要么是D【x-1】【y-1】的情况下,如果word1【x】==word2【y】,+0;要么是word2【y】改为word1【x】,+1。

这里借用斯坦福公开课的例子:

以第一个单词"INTENTION"和第二个单词"EXECUTION"为例,看下面的图



具体代码如下:

public static int minDistance(String word1, String word2) {int[][] table=new int[word1.length()+1][word2.length()+1];int a,b,c;for(int i=0;i<table.length;i++){table[i][0]=i;}for(int i=0;i<table[0].length;i++){table[0][i]=i;}for(int i=1;i<=word1.length();i++){for(int j=1;j<=word2.length();j++){a=table[i-1][j]+1;b=table[i][j-1]+1;c=table[i-1][j-1]+(int)(word1.charAt(i-1)==word2.charAt(j-1)?0:1);//System.out.println(table[i-1][j-1]+":");//System.out.println(word1.charAt(i-1)==word2.charAt(j-1)?0:2);//System.out.println(table[i-1][j-1]+"table["+i+"]["+j+"]"+a+":"+b+":"+c);table[i][j]=Math.min(a, Math.min(b, c));}}return table[word1.length()][word2.length()];    }

0 0
原创粉丝点击