LeetCode583——Delete Operation for Two Strings解题报告

Leetcode583 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:
The length of given words won't exceed 500.
Characters in given words can only be lower-case letters.

简单来说就是给你两个字符串,做几次操作可以使得两个串相等(每次操作只能删除一个字符)。

思路

递归的解法

那么我们应该可以想到这其实就是求两个字符串的最长公共子串。因为只要我们知道了这两个字符串的最长公共子串,答案就是s1.length + s2.length - 2 * longest common string。
求最长公共子串的话可以进行递归求解。

function getLongestCommonString (s1, s2, m, n) {
    if (s[m] === s[n]) {
        return arguments.callee(s1, s2, m - 1, n - 1)
    } else {
        return Math.max(arguments.callee(s1, s2, m, n - 1), arguments.callee(s1, s2, m - 1, n))
    }
}

其实看代码就很明白,如果两个串最后一个字符对上了,那么它的结果就是s1[0:m-1]和s2[0:n-1]的最长公共子串数量加上1。如果对不上,那就是等于s1[0:m-1]和s2[0:n]的最长公共子串数量和s1[0:m]和s2[0:n-1]的最长公共子串数量两者的最大值。进行一次递归就可以得到结论,最后用计算公式得到操作次数。

dp的解法

这道题也可以用dp来做,算法上和递归解答思路是相近的。我们用二维数组来存状态。dp[i][j]表示s1[0:i]和s2[0:j]的最长公共子串,那么我们只需要在字符对上时,dp[i][j] = dp[i - 1][j - 1] + 1,对不上时,dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])就行了,注意一下边界值即可。

/**
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
var minDistance = function(word1, word2) {
    if (word1.length === 0 || word2.length === 0) {
        return word1.length > word2.length ? word1.length:word2.length
    }
    var store = new Array()
    for (var i = 0; i < 501; i++) {
        store[i] = new Array()
    }
    for (var i = 0; i < word1.length; i++) {
        for (var k = 0; k < word2.length; k++) {
            if (word1[i] === word2[k]) {
                if (i === 0) {
                    store[0][k] = 1
                } else if (k === 0) {
                    store[i][0] = 1
                } else {
                    store[i][k] = store[i - 1][k - 1] + 1
                }
            } else {
                if (i === 0 && k === 0) {
                    store[0][0] = 0                    
                } else if (i === 0) {
                    store[0][k] = store[0][k - 1]
                } else if (k === 0) {
                    store[i][0] = store[i - 1][0]
                } else {
                    store[i][k] = Math.max(store[i][k - 1], store[i - 1][k])
                }
            }
        }
    }
    return word1.length + word2.length - 2 * store[word1.length - 1][word2.length - 1]
};

代码效率不咋的。。。

你可能感兴趣的:(LeetCode583——Delete Operation for Two Strings解题报告)