Skip to content

Commit 6b0a45b

Browse files
authored
Create 1143_Longest_Common_Subsequence.md
1 parent 2c2f9e2 commit 6b0a45b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

1143_Longest_Common_Subsequence.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## 1143. Longest Common Subsequence
2+
3+
```
4+
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
5+
6+
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
7+
8+
For example, "ace" is a subsequence of "abcde".
9+
A common subsequence of two strings is a subsequence that is common to both strings.
10+
11+
12+
13+
Example 1:
14+
15+
Input: text1 = "abcde", text2 = "ace"
16+
Output: 3
17+
Explanation: The longest common subsequence is "ace" and its length is 3.
18+
Example 2:
19+
20+
Input: text1 = "abc", text2 = "abc"
21+
Output: 3
22+
Explanation: The longest common subsequence is "abc" and its length is 3.
23+
Example 3:
24+
25+
Input: text1 = "abc", text2 = "def"
26+
Output: 0
27+
Explanation: There is no such common subsequence, so the result is 0.
28+
29+
30+
Constraints:
31+
32+
1 <= text1.length, text2.length <= 1000
33+
text1 and text2 consist of only lowercase English characters.
34+
```
35+
36+
```python
37+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
38+
size1 = len(text1)
39+
size2 = len(text2)
40+
41+
dp = [[0] * (size2+1) for _ in range(size1+1)]
42+
43+
# print(dp)
44+
45+
for i in range(1, size1+1):
46+
for j in range(1, size2+1):
47+
48+
if text1[i-1] == text2[j-1]:
49+
dp[i][j] = dp[i-1][j-1]+1
50+
else:
51+
dp[i][j] = max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
52+
53+
return dp[-1][-1]
54+
```
55+
56+
```
57+
Runtime: 476 ms, faster than 38.20% of Python3 online submissions for Longest Common Subsequence.
58+
Memory Usage: 21.9 MB, less than 78.67% of Python3 online submissions for Longest Common Subsequence.
59+
```

0 commit comments

Comments
 (0)