Level:
Hard
题目描述:
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"Output: 3Explanation: horse -> rorse (replace 'h' with 'r')rorse -> rose (remove 'r')rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"Output: 5Explanation: intention -> inention (remove 't')inention -> enention (replace 'i' with 'e')enention -> exention (replace 'n' with 'x')exention -> exection (replace 'n' with 'c')exection -> execution (insert 'u')
思路分析:
动态规划的思想,dp[i] [j]代表将word1前i个字符转换成word2前j个字符所需要的操作次数。
如果word1[i]==word2[j],那么dp[i] [j]=dp[i-1] [j-1]。
如果word1[i]不等于word2[j],需要找出插入元素,删除元素,替换元素中最小的操作,然后加一。
dp[i] [j-1]表示word1前i个可以表示word2前j-1个,那么要表示前j个,只能执行插入操作。
dp[i-1] [j]表示word1前i-1个可以表示word2前j个,那么要前i个表示前j个,只能执行删除操作。
dp[i-1] [j-1]表示word1前i-1个可以表示word2前j-1个,那么要前i个表示前j个,只能执行替换操作。
则dp[i] [j]=min(dp[i-1] [j],dp[i] [j],dp[i-1] [j-1])+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;i++){ dp[i][0]=i; //单纯的删除操作 } for(int i=0;i<=n;i++){ dp[0][i]=i; //单纯的插入操作 } for(int i=0;i