Leetcode : EditDistance(编程之美3.3)

来源:互联网 发布:梦幻诛仙龙晶合成算法 编辑:程序博客网 时间:2024/06/03 03:03
    假如我们要将字符串str1变成str2
    sstr1(i)是str1的子串,范围[0到i),sstr1(0)是空串
    sstr2(j)是str2的子串,同上
    d(i,j)表示将sstr1(i)变成sstr2(j)的编辑距离

    首先d(0,t),0<=t<=str1.size()和d(k,0)是很显然的。
    当我们要计算d(i,j)时,即计算sstr1(i)到sstr2(j)之间的编辑距离,
    此时,设sstr1(i)形式是somestr1c;sstr2(i)形如somestr2d的话,
    将somestr1变成somestr2的编辑距离已知是d(i-1,j-1)
    将somestr1c变成somestr2的编辑距离已知是d(i,j-1)
    将somestr1变成somestr2d的编辑距离已知是d(i-1,j)
    那么利用这三个变量,就可以递推出d(i,j)了:
    如果c==d,显然编辑距离和d(i-1,j-1)是一样的
    如果c!=d,情况稍微复杂一点,

    1. 如果将c替换成d,编辑距离是somestr1变成somestr2的编辑距离 + 1,也就是d(i-1,j-1) + 1
    2. 如果在c后面添加一个字d,编辑距离就应该是somestr1c变成somestr2的编辑距离 + 1,也就是d(i,j-1) + 1
    3. 如果将c删除了,那就是要将somestr1编辑成somestr2d,距离就是d(i-1,j) + 1

      那最后只需要看着三种谁最小,就采用对应的编辑方案了。

    递推公式出来了,程序也就出来了。

import java.util.Scanner;public class EditDistance {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubScanner scan = new Scanner(System.in);String word1 = scan.nextLine();String word2 = scan.nextLine();EditDistance ed = new EditDistance();System.out.println(ed.minDistance(word1, word2));}public int minDistance(String word1, String word2) {int d[][] = new int[word1.length() + 1][word2.length() + 1];for (int i = 0; i < word1.length() + 1; i++) {d[i][0] = i;}for (int j = 0; j < word2.length() + 1; j++) {d[0][j] = j;}for (int i = 1; i < word1.length() + 1; i++) {for (int j = 1; j < word2.length() + 1; j++) {if (word1.charAt(i - 1) == word2.charAt(j - 1)) {d[i][j] = d[i - 1][j - 1];} else {d[i][j] = min(d[i - 1][j], d[i][j - 1], d[i - 1][j - 1]) + 1;}}}return d[word1.length()][word2.length()];}public int min(int a, int b, int c) {int temp = (b > c) ? c : b;return (a > temp) ? temp : a;}}


0 0
原创粉丝点击