|
| 1 | +# Longest Common Subsequence |
| 2 | +# |
| 3 | +# [Medium] [AC:58.4% 139K of 238K] [filetype:python3] |
| 4 | +# |
| 5 | +# Given two strings text1 and text2, return the length of their longest common subsequence. |
| 6 | +# |
| 7 | +# A subsequence of a string is a new string generated from the original string with some |
| 8 | +# characters(can be none) deleted without changing the relative order of the |
| 9 | +# remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is |
| 10 | +# not). A common subsequence of two strings is a subsequence that is common to both strings. |
| 11 | +# |
| 12 | +# If there is no common subsequence, return 0. |
| 13 | +# |
| 14 | +# Example 1: |
| 15 | +# |
| 16 | +# Input: text1 = "abcde", text2 = "ace" |
| 17 | +# |
| 18 | +# Output: 3 |
| 19 | +# |
| 20 | +# Explanation: The longest common subsequence is "ace" and its length is 3. |
| 21 | +# |
| 22 | +# Example 2: |
| 23 | +# |
| 24 | +# Input: text1 = "abc", text2 = "abc" |
| 25 | +# |
| 26 | +# Output: 3 |
| 27 | +# |
| 28 | +# Explanation: The longest common subsequence is "abc" and its length is 3. |
| 29 | +# |
| 30 | +# Example 3: |
| 31 | +# |
| 32 | +# Input: text1 = "abc", text2 = "def" |
| 33 | +# |
| 34 | +# Output: 0 |
| 35 | +# |
| 36 | +# Explanation: There is no such common subsequence, so the result is 0. |
| 37 | +# |
| 38 | +# Constraints: |
| 39 | +# |
| 40 | +# 1 <= text1.length <= 1000 |
| 41 | +# |
| 42 | +# 1 <= text2.length <= 1000 |
| 43 | +# |
| 44 | +# The input strings consist of lowercase English characters only. |
| 45 | +# |
| 46 | +# [End of Description]: |
| 47 | +# memo |
| 48 | +# key point is creating the dp array |
| 49 | +class Solution: |
| 50 | + def longestCommonSubsequence(self, text1: str, text2: str) -> int: |
| 51 | + memo = {} |
| 52 | + |
| 53 | + def dp(i, j): |
| 54 | + # base case |
| 55 | + if i == -1 or j == -1: |
| 56 | + return 0 |
| 57 | + if (i, j) in memo: |
| 58 | + return memo[(i, j)] |
| 59 | + if text1[i] == text2[j]: |
| 60 | + # find the common character |
| 61 | + memo[(i, j)] = dp(i - 1, j - 1) + 1 |
| 62 | + return memo[(i, j)] |
| 63 | + else: |
| 64 | + memo[(i, j)] = max(dp(i - 1, j), dp(i, j - 1)) |
| 65 | + return memo[(i, j)] |
| 66 | + |
| 67 | + return dp(len(text1) - 1, len(text2) - 1) |
0 commit comments