标签:
题目描述:
给出两个单词word1和word2,计算出将word1 转换为word2的最少操作次数。
你总共三种操作方法:
返回 3
1 public class Solution { 2 /** 3 * @param word1 & word2: Two string. 4 * @return: The minimum number of steps. 5 */ 6 public int minDistance(String word1, String word2) { 7 // write your code here 8 int[][] dp = new int[word1.length()+1][word2.length()+1]; 9 10 for(int i=1;i<=word1.length();i++) 11 dp[i][0] = i; 12 13 for(int i=1;i<=word2.length();i++) 14 dp[0][i] = i; 15 16 for(int i=0;i<word1.length();i++){ 17 for(int j=0;j<word2.length();j++){ 18 if(word1.charAt(i) == word2.charAt(j)){ 19 dp[i+1][j+1] = Math.min(dp[i][j],Math.min(dp[i][j+1],dp[i+1][j])+1); 20 }else{ 21 dp[i+1][j+1] = Math.min(dp[i][j+1]+1,Math.min(dp[i][j],dp[i+1][j])+1); 22 } 23 } 24 } 25 return dp[word1.length()][word2.length()]; 26 } 27 }
标签:
原文地址:http://www.cnblogs.com/xiaocainiao2hao/p/5361379.html