LeetCode 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: 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  

思路

DP 题目,可以转换为LCS问题,参考YouTube

Swift 题解

func minDistance(_ word1: String, _ word2: String) -> Int {  
        var dp = Array(repeating: Array(repeating: 0, count: word2.count + 1), count: word1.count + 1)
        let w1 = Array(word1)
        let w2 = Array(word2)

        for i in 0...w1.count {
            for j in 0...w2.count {
                if i == 0 || j == 0 {
                    dp[i][j] = 0
                } else {
                    dp[i][j] = w1[i - 1] == w2[j - 1] ? (dp[i-1][j-1] + 1) : max(dp[i][j-1], dp[i-1][j])
                }
            }
        }

        let lcs = dp[w1.count][w2.count]
        return w1.count + w2.count - 2 * lcs
    }

chenbo

编程爱好者

Singapore