leetcode583. Delete Operation for Two Strings

来源:互联网 发布:美工提成怎么算 编辑:程序博客网 时间:2024/06/06 04:00


题目

Given two words word1 and word2, find the minimum number of steps required to makeword1 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.

思路


要让操作数最少,那么就是说留下的应当是两者的最大公共子序列,那么问题就转换成求LCS长度的问题了。只要先找到两者的最长公共子序列的,然后分别做差求和就行了。LCS的话还是用DP做就好了,并且只要求长度就行了。table[i][j],表示匹配到s1[i],s2[j]时的LCS长度。转换方程s1[i-1]==s2[j-1] :table[i][j] = table[i - 1][j - 1] + 1;  s1[i-1]!=s2[j-1] :table[i][j] =max(table[i][j-1], table[i-1][j]);

代码

class Solution {public:    int minDistance(string word1, string word2) {        int table[501][501];        for (int i = 1; i < word1.length()+1; i ++) {            for (int j = 1; j < word2.length()+1; j ++) {                if (word1[i - 1] == word2[j - 1]) {                    table[i][j] = table[i - 1][j - 1] + 1;                } else {                    table[i][j] = max(table[i][j-1], table[i-1][j]);                }            }        }                int lcs =table[word1.length()][word2.length()];        return (word1.length() - lcs) + (word2.length() - lcs);    }};

原创粉丝点击