LeetCode:M-583. Delete Operation for Two Strings

来源:互联网 发布:mac 终端翻墙 编辑:程序博客网 时间:2024/06/05 04:33

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: 2Explanation: 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.

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