LeetCode: Delete Operation For Two Strings Solution
1/**2 * @param {string} word13 * @param {string} word24 * @return {number}5 */6var minDistance = function (word1, word2) {7 const getLcs = (word1, word2) => {8 const getKey = (i, j) => `${i}-${j}`910 const recursion = (word1, word2, i, j, memo = {}) => {11 if (memo[getKey(i, j)] !== undefined) {12 return memo[getKey(i, j)]13 }1415 if (i === 0 || j === 0) {16 return 017 }1819 if (word1[i - 1] === word2[j - 1]) {20 return (memo[getKey(i, j)] =21 1 + recursion(word1, word2, i - 1, j - 1, memo))22 }2324 return (memo[getKey(i, j)] = Math.max(25 recursion(word1, word2, i - 1, j, memo),26 recursion(word1, word2, i, j - 1, memo)27 ))28 }2930 return recursion(word1, word2, word1.length, word2.length)31 }3233 return word1.length + word2.length - 2 * getLcs(word1, word2)34}
Comments
Loading comments...
Tags
leetcode
string
recursion
dynamic programming
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Super Palindromes
May 9, 2021