leetcode72:Edit Distance

leetcode72:Edit Distance_第1张图片

思路:设dp[i][j]表示word1中0-i个字符转换成word2中0-j个字符需要的最少次数,先对0行和0列所有元素进行初始化,然后从1行1列开始往后递推,最终将dp数组填充满,dp[row][col]即为最终结果。

状态转移方程为:

if(word1[i]==word2[j]):

dp[i][j]=dp[i-1][j-1];

else:

dp[i][j]=Math.min(dp[i-1][j-1]+1, Math.min(dp[i][j-1]+1, dp[i-1][j]+1));

以“ros”和“horse”为例:

  null h o r s e
null 0 1 2 3 4 5
r 1 1 2 2 3 4
o 2 2 1 2 3 4
s 3 2 2 2 2 3

代码:

public class EditDistance {

	public static void main(String[] args) {

		System.out.println(minDistance("ros","horse"));

	}

	public static 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 <= len2; i++) {
			dp[0][i]=i;
		}
		for (int i = 0; i <= len1; i++) {
			dp[i][0]=i;
		}
		
		for (int i = 1; i <= len1; i++) {
			for (int j = 1; j <= len2; j++) {
				if(word1.charAt(i-1)==word2.charAt(j-1))
					dp[i][j]=dp[i-1][j-1];
				else
					dp[i][j]=Math.min(dp[i-1][j-1]+1, Math.min(dp[i][j-1]+1, dp[i-1][j]+1));
			
			}
			
		}
		
//		for (int i = 0; i < dp.length; i++) {
//			for (int j = 0; j < dp[0].length; j++) {
//				System.out.print(dp[i][j]+" ");
//			}
//			System.out.println();
//		}
		
		
		return dp[len1][len2];
	}
}

输出:

你可能感兴趣的:(JavaSE,算法,面试准备,刷题)