leetcode Edit Distance

Edit Distance 原题地址:

https://oj.leetcode.com/problems/edit-distance/

The edit distance of two strings, s1 and s2, is defined as the minimum number of point mutations required to change s1 into s2, where a point mutation is one of:

  1. change a letter,
  2. insert a letter or
  3. delete a letter

计算两个字符串s1+ch1, s2+ch2编辑距离有这样的性质:

1.         d(s1,””) = d(“”,s1) = |s1|    d(“ch1”,”ch2”) = ch1 == ch2 ? 0 : 1;

2.         d(s1+ch1,s2+ch2) = min(d(s1,s2)+ ch1==ch2 ? 0 : 1 , d(s1+ch1,s2), d(s1,s2+ch2) );

  第一个性质是显然的。

              第二个性质:          由于我们定义的三个操作来作为编辑距离的一种衡量方法。

                                          于是对ch1,ch2可能的操作只有

1.         ch1变成ch2

2.         s1+ch1后删除ch1              d = (1+d(s1,s2+ch2))

3.         s1+ch1后插入ch2              d = (1 + d(s1+ch1,s2))

                                          对于23的操作可以等价于:

                                          _2.   s2+ch2后添加ch1              d=(1+d(s1,s2+ch2))

                                          _3.   s2+ch2后删除ch2              d=(1+d(s1+ch1,s2))

                     因此可以得到计算编辑距离的性质2

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值