LeetCode:M-583. Delete Operation for Two Strings
2017-09-13 11:02
656 查看
LeetCode链接
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:
Note:
The length of given words won't exceed 500.
Characters in given words can only be lower-case letters.
class Solution {
//求最长公共子序列
public int minDistance(String word1, String word2) {
if(word1==null || word2==null)
return 0;
int n1 = word1.length();
int n2 = word2.length();
if(n1==0 || n2==0)
return Math.max(n1,n2);
int[][] dp = new int[n1][n2];
for(int i=0; i<n1; i++){
for(int j=0; j<n2; j++){
if(word1.charAt(i)==word2.charAt(j))
dp[i][j] = (i==0||j==0)?1:(dp[i-1][j-1]+1);
dp[i][j] = Math.max(dp[i][j], Math.max(i==0?0:dp[i-1][j], j==0?0:dp[i][j-1]));
}
}
return n1+n2-2*dp[n1-1][n2-1];
}
}
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:
The length of given words won't exceed 500.
Characters in given words can only be lower-case letters.
class Solution {
//求最长公共子序列
public int minDistance(String word1, String word2) {
if(word1==null || word2==null)
return 0;
int n1 = word1.length();
int n2 = word2.length();
if(n1==0 || n2==0)
return Math.max(n1,n2);
int[][] dp = new int[n1][n2];
for(int i=0; i<n1; i++){
for(int j=0; j<n2; j++){
if(word1.charAt(i)==word2.charAt(j))
dp[i][j] = (i==0||j==0)?1:(dp[i-1][j-1]+1);
dp[i][j] = Math.max(dp[i][j], Math.max(i==0?0:dp[i-1][j], j==0?0:dp[i][j-1]));
}
}
return n1+n2-2*dp[n1-1][n2-1];
}
}
相关文章推荐
- LeetCode - 583. Delete Operation for Two Strings
- leetcode 583. Delete Operation for Two Strings
- leetcode 583. Delete Operation for Two Strings 问题转换+最长公共子串 + DP动态规划
- [LeetCode] 583. Delete Operation for Two Strings
- [Leetcode] 583. Delete Operation for Two Strings 解题报告
- [leetcode]583. Delete Operation for Two Strings
- [LeetCode]583. Delete Operation for Two Strings
- 【Leetcode】583. Delete Operation for Two Strings
- [LeetCode] 583. Delete Operation for Two Strings 两个字符串的删除操作
- [leetcode] 583. Delete Operation for Two Strings
- 583.Delete Operation for Two Strings
- [leetcode 583] Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- LeetCode Delete Operation for Two Strings
- 第十三周:( LeetCode583) Delete Operation for Two Strings(c++)
- 583. Delete Operation for Two Strings
- [python]leetcode(72). Edit Distance AND (583). Delete Operation for Two Strings
- LeetCode 583: Delete Operation for Two Strings
- [LeetCode] Delete Operation for Two Strings 两个字符串的删除操作
- 【Leetcode-Medium-583】Delete Operation for Two Strings