583.Delete Operation for Two Strings

来源:互联网 发布:频率发生器软件 编辑:程序博客网 时间:2024/06/04 18:53

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: 2Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
  • 题目大意:给定两个单词,每次可以删除一个字符,找到最少的步骤,使得两个单词相等。

  • 思路:运用最长公共子序列思路,先找出两个单词的最长公共子序列的长度,之后返回word1.length() - val + word2.length() - val。

  • 代码

    package String;/*** @Author OovEver* @Date 2017/12/8 21:32*/public class LeetCode583 {  public int minDistance(String word1, String word2) {//        dp代表两个string字符串最长公共字符串的长度      int[][] dp = new int[word1.length() + 1][word2.length() + 1];      for(int i=0;i<=word1.length();i++) {          for(int j=0;j<=word2.length();j++) {              if (i == 0 || j == 0) {                  dp[i][j] = 0;              } else {                  dp[i][j] = (word1.charAt(i - 1) == word2.charAt(j - 1)) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);              }          }      }      int val = dp[word1.length()][word2.length()];      return word1.length() - val + word2.length() - val;  }}
原创粉丝点击