leetcode 72 Edit Distance

来源:互联网 发布:数据结构与算法百度云 编辑:程序博客网 时间:2024/05/21 01:48

编辑距离


问题描述

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

Subscribe to see which companies asked this question

思路

以前遇到的编辑距离总有点摸不着头脑,这次听了曹博士的直播coding后发现原来可以转化为字符串对齐问题啊,这样我就明朗多了
换个角度思考问题,变为字符串“对齐问题”:
S= “ABCF” T = “DBFG”

这里写图片描述
对应位置相同不扣分,不同则扣一分(修改)
两个特殊字符“-”不会对应
S位置“-”代表增加字符
T位置“-”代表删掉字符
使扣分最少

public int same (int a,int b) {        return a == b ? 0:1;//相同不扣分,不同的扣一分    }    public int minDistance(String word1, String word2) {        int len1 = word1.length();        int len2 = word2.length();        int [][]dp = new int[len1 + 1][len2 + 1];        for (int i = 0;i < len1 + 1; i++) {            for (int j = 0; j < len2 + 1;j++) {                if (i == 0) {                    dp[i][j] = j;                } else if (j == 0) {                    dp[i][j] = i;                } else{                    //这里分为三种情况//                  1:dp[i - 1][j - 1]+same(i,j),对应s与t在i和j的位置对齐。//                  2:dp[i - 1][j] + 1 对应s第i个字符与T的“-”对齐,s应该删除一个//                  3:dp[i][ j - 1] + 1 对应s中的“-”与T中的“j - 1”对齐,s应该增加一个                    //这里的下标需要注意一下,dp中的i - 1,j - 1其实对应的比word中的还要少一位。                    dp[i][j] = Math.min(dp[i - 1][j - 1] + same(word1.charAt(i - 1),word2.charAt(j - 1)), Math.min(dp[i][j - 1] + 1,dp[i - 1][j] + 1));                }            }        }        return dp[len1][len2];    }

如果我们想做一下空间的优化,我们可以用一维,用到一些小技巧进行记录就可以了。

0 0