您的位置:首页 > 运维架构

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:

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];
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息