# 583. Delete Operation for Two Strings

[583. Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/)

兩個單字需要刪掉的字元，恰好是他們沒有重疊的字元，他們沒有重疊的字元，所以找出兩個字元的最長公共子字串，分別刪掉後，剩下的字元就是最少的刪除操作了。

```python
class Solution:
    def longestCommonSubsequence(self, word1: str, word2: str) -> int:
        @lru_cache(None)
        def helper(i, j):
            if i == len(word1) or j == len(word2):
                return 0
            if word1[i] == word2[j]:
                return 1 + helper(i+1, j+1)
            else:
                return max(helper(i+1, j), helper(i, j+1))
        return helper(0, 0)


    def minDistance(self, word1: str, word2: str) -> int:
        lcs = self.longestCommonSubsequence(word1, word2)

        return len(word1) + len(word2) - 2 * lcs
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://garylai.gitbook.io/algorithm-and-data-structure/problems/dynamic-programming/longest-common-subsequence/delete-operation-for-two-strings.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
