# LeetCode: Delete Operation For Two Strings Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**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}`9
10    const recursion = (word1, word2, i, j, memo = {}) => {11      if (memo[getKey(i, j)] !== undefined) {12        return memo[getKey(i, j)]13      }14
15      if (i === 0 || j === 0) {16        return 017      }18
19      if (word1[i - 1] === word2[j - 1]) {20        return (memo[getKey(i, j)] =21          1 + recursion(word1, word2, i - 1, j - 1, memo))22      }23
24      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    }29
30    return recursion(word1, word2, word1.length, word2.length)31  }32
33  return word1.length + word2.length - 2 * getLcs(word1, word2)34}```

## Tags

leetcode

string

recursion

dynamic programming

## Next Post

LeetCode: Maximum Population Year

May 9, 2021

Search Posts