Skip to content

Commit fd7eb82

Browse files
authored
Add files via upload
1 parent edb55fe commit fd7eb82

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
516. Longest Palindromic Subsequence(Medium)
2+
3+
Given a string s, find the longest palindromic subsequence's length in s.
4+
5+
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
6+
7+
8+
9+
Example 1:
10+
11+
Input: s = "bbbab"
12+
Output: 4
13+
Explanation: One possible longest palindromic subsequence is "bbbb".
14+
Example 2:
15+
16+
Input: s = "cbbd"
17+
Output: 2
18+
Explanation: One possible longest palindromic subsequence is "bb".
19+
20+
21+
Constraints:
22+
23+
1 <= s.length <= 1000
24+
s consists only of lowercase English letters.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# 1) Top down
2+
3+
class Solution:
4+
def longestPalindromeSubseq(self, s: str) -> int:
5+
# dp(i, j) := LPS's length in s[i..j]
6+
@functools.lru_cache(None)
7+
def dp(i: int, j: int) -> int:
8+
if i > j:
9+
return 0
10+
if i == j:
11+
return 1
12+
if s[i] == s[j]:
13+
return 2 + dp(i + 1, j - 1)
14+
return max(dp(i + 1, j), dp(i, j - 1))
15+
16+
return dp(0, len(s) - 1)
17+
18+
# 2) Bottom up
19+
20+
class Solution:
21+
def longestPalindromeSubseq(self, s: str) -> int:
22+
n = len(s)
23+
# dp[i][j] := LPS's length in s[i..j]
24+
dp = [[0] * n for _ in range(n)]
25+
26+
for i in range(n):
27+
dp[i][i] = 1
28+
29+
for d in range(1, n):
30+
for i in range(n - d):
31+
j = i + d
32+
if s[i] == s[j]:
33+
dp[i][j] = 2 + dp[i + 1][j - 1]
34+
else:
35+
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
36+
37+
return dp[0][n - 1]

0 commit comments

Comments
 (0)