[leetcode] 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.

分析:题目翻译一下:两个字符串word1、word2,要求删除一些字符使得两个字符串最后相等,求删除最少字符的个数。一看又是字符串+极值的问题,虽然不是很明显的动态规划,但也一定要先从动态规划来下手。参考 Minimum ASCII Delete Sum for Two Strings 的方法,我们不难得到下面的代码:
 1 class Solution {
 2     public int minDistance(String word1, String word2) {
 3         int[][]dp = new int[word1.length()+1][word2.length()+1];
 4         for ( int j = 1 ; j <= word2.length() ; j ++ )  dp[0][j] = dp[0][j-1] + 1;
 5         for ( int i = 1 ; i <= word1.length() ; i ++ )  dp[i][0] = dp[i-1][0] + 1;
 6         for ( int i = 1 ; i <= word1.length() ; i ++ ){
 7             for ( int j = 1 ; j <= word2.length() ; j ++ ){
 8                 if ( word1.charAt(i-1) == word2.charAt(j-1) ) dp[i][j] = dp[i-1][j-1];
 9                 else dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1]) + 1;
10             }
11         }
12         return dp[word1.length()][word2.length()];
13     }
14 }

      运行时间39ms,击败92.49%的提交。

posted @ 2018-07-17 16:48  Lin.B  阅读(122)  评论(0编辑  收藏  举报