Skip to content

Commit 14c86e8

Browse files
committedNov 28, 2020
feat: lcs
1 parent 1b921c0 commit 14c86e8

5 files changed

+43
-0
lines changed
 
File renamed without changes.
File renamed without changes.

‎dp.longest-common-subsequence.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution:
2+
"""
3+
1143. 最长公共子序列
4+
https://leetcode-cn.com/problems/longest-common-subsequence/
5+
给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。
6+
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
7+
例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。
8+
若这两个字符串没有公共子序列,则返回 0。
9+
"""
10+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
11+
m, n = len(text1), len(text2)
12+
# 构件状态数组
13+
dp = [[0] * (n + 1) for _ in range(m + 1)]
14+
15+
for i in range(1, m + 1):
16+
for j in range(1, n + 1):
17+
if text1[i - 1] == text2[j - 1]:
18+
dp[i][j] = 1 + dp[i-1][j-1]
19+
else:
20+
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
21+
22+
return dp[-1][-1]
23+
24+
# 暴力求解
25+
def longestCommonSubsequenceByForce(self, text1: str, text2: str) -> int:
26+
def dp(i, j):
27+
# 空串
28+
if i == -1 or j == -1:
29+
return 0
30+
31+
# 找到 lcs 元素
32+
if text1[i] == text2[j]:
33+
return dp(i - 1, j - 1) + 1
34+
# 看看谁的 lcs 最长,就选谁
35+
else:
36+
return max(dp(i - 1, j), dp(i, j - 1))
37+
38+
# 首次执行
39+
return dp(len(text1) - 1, len(text2) - 1)
40+
41+
42+
so = Solution()
43+
print(so.longestCommonSubsequence('abcde', 'ace'))
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)
Please sign in to comment.