编辑距离

	int[][] memo = null; // 备忘录
	
	int solve(String word1, String word2, int c1, int c2)
	{
		int a, b, c ;
		int n1 = word1.length(); 
		int n2 = word2.length();
		
		if (c1 == n1 && c2 == n2)
			return 0;
		
		if (c1 == n1)
			return n2-c2; // 添上缺失的c2的部分
		
		if (c2 == n2)
			return n1-c1; // 砍掉c1后面的字符
		
		// 如果计算过
		if (memo[c1][c2] != 0)
			return memo[c1][c2];
		
		if (word1.charAt(c1) == word2.charAt(c2))
		{
			return solve(word1, word2, c1+1, c2+1); // 继续比较下一个字符
		}
		else
		{
			a = solve(word1, word2, c1, c2+1); // 插入一个字符
			b = solve(word1, word2, c1+1, c2+1); // 替换一个字符
			c = solve(word1, word2, c1+1, c2); // 删除一个字符
			memo[c1][c2] = min(a, b, c) + 1;
			return memo[c1][c2];
		}
	}
	
	int min(int x, int y, int z)
	{
		return Math.min(Math.min(x, y), z);
	}
	
	public int minDistance(String word1, String word2) 
	{
		if (word1.isEmpty())
			return word2.length();
		
		if (word2.isEmpty())
			return word1.length();
		
		// 初始化备忘录
		memo = new int[word1.length()+1][word2.length()+1];
		return solve(word1, word2, 0, 0);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值