标签:
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
分析:
给出两个单词word1和word2,计算出将word1 转换为word2的最少操作次数。
你总共三种操作方法:
样例
给出 work1="mart" 和 work2="karma"
返回 3
使用动态规划来解题,
定义一个动态数组dp[word1.length + 1][word2.length + 1],
之所以是word1和word2的长度加1,是因为从0开始变化到每一位,总共是长度+1总情况,
dp[i][j] 代表的是从word1的前i个字符转化到word2的前j个字符,需要的最少的次数。
每次循环中,分为两种情况,比如word1遍历到了第i个字符,字符为a,word2遍历到了第j个字符,字符为b,
(1) 如果a == b, 不需要做任何编辑操作,dp[i][j] = dp[i-1][j-1]
(2)如果a != b
操作方法一:插入字符的方式,在word1中插入b,那么dp[ i ] [ j ]= dp[ i ][ j - 1]+ 1;
操作方法二:删除字符的方式,在word1中将a删除,那么dp[ i ] [ j ] = dp[ i - 1] [ j ] + 1;
操作方法三:替换字符的方式,在word1中将a替换为b, 那么dp [i - 1][j - 1] + 1;
取这三者的最小值作为最少操作次数。
返回dp[word1.length + 1][word2.length + 1]
public class Solution { public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 0; i < m + 1; i++) { dp[i][0] = i; } for (int i = 0; i < n + 1; i++) { dp[0][i] = i; } for (int i = 1; i < m + 1; i++) { for (int j = 1; j < n + 1; j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])); } } } return dp[m][n]; } }
标签:
原文地址:http://www.cnblogs.com/iwangzheng/p/5793115.html