583.Delete Operation for Two Strings
題目連結
難易度:Medium
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
2
3Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
大意是,求最小的刪除次數讓兩字串相等,也就是找出最長公共子字串LCS(Longest Common Subsequence)的長度,這樣兩字串所需刪除數最少,而刪除的步數即等於兩字串長度相加並扣除兩倍的LCS長度。
思路
將word1、word2字串逐步拆解為兩部份sub1、e1,sub2、e2(e1、e2代表最後一字元)
使用DP,用一二維陣列lcslen來存lcs長度,此時會分為三種可能:
- 第一種為當e1 == e2 (表示兩字串某部份最後一字元相等時),這時的lcslen就等同於lcslen[sub1][sub2]+1,+1表示相同的值所以長度+1。
- 第二種情況為e1 !== e2,此時lcslen又可分為兩種,lcslen[sub1][word2]、lcslen[word1][sub2],找出兩者最大即可
解題
1 | var minDistance = function(word1, word2) { |