LeetCode 583 Delete Operation for Two Strings 删除两个字符串的不同部分使两个字符串相同,求删除的步数
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.
Example 1:
Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
Note:
1.The length of given words won't exceed 500.
2.Characters in given words can only be lower-case letters.
1 class Solution { 2 public: 3 int minDistance(string word1, string word2) { 4 int n1=word1.size(); 5 int n2=word2.size(); 6 int dp[n1+1][n2+1]; 7 8 for(int i=0;i<=n1;++i) 9 { 10 for(int j=0;j<=n2;++j) 11 { 12 if(i==0||j==0) 13 dp[i][j]=0; 14 else 15 { 16 if(word1[i-1]==word2[j-1]) 17 dp[i][j]=dp[i-1][j-1]+1; 18 else 19 dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 20 } 21 } 22 } 23 return n1+n2-dp[n1][n2]*2; 24 } 25 };