Word distance Leetcode.

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


题目不难,只是想到 各种edit的方法就有莫名的恐惧... 其实就是 换, 加, 减,于是就可以 从三个方向来update i,j  也就是 i -1, j - 1; i -1,j ; i, j-1. 

public class Solution {
    public int minDistance(String word1, String word2) {
	
	int m = word1.length(), n = word2.length();
	if(m == 0 && n == 0) return 0;
	if(m == 0) return n;
	if(n == 0) return m;
	int[][] dp = new int[m+1][n+1];
	for(int i = 0; i <= m; i ++) dp[i][0] = i;
	for(int j = 0; j <= n; j ++) dp[0][j] = j;
	dp[0][0] = 0;
	for(int i = 1; i <= m; i++)
		for(int j = 1; j <= n; j++){
							
			if(word1.charAt(i-1) == word2.charAt(j-1)) 
				dp[i][j] = dp[i-1][j-1];
			else{
				int temp = dp[i-1][j-1];
				if(temp > dp[i][j-1]) temp = dp[i][j-1];
				if(temp > dp[i-1][j]) temp = dp[i-1][j];
				dp[i][j] = temp + 1;
			}
			 
		}
	return dp[m][n];
}
}



你可能感兴趣的:(Word distance Leetcode.)