-
Notifications
You must be signed in to change notification settings - Fork 9
/
longest_palindromic_subsequence.py
98 lines (74 loc) · 2.45 KB
/
longest_palindromic_subsequence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""
https://leetcode.com/problems/longest-palindromic-subsequence/
Given a string s, find the longest palindromic subsequence's length in s.
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.
Example 1:
Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".
Example 2:
Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".
Constraints:
1 <= s.length <= 1000
s consists only of lowercase English letters.
"""
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
@lru_cache(None)
def rec(i, j):
if i == j:
return 1
elif i > j:
return 0
if s[i] == s[j]:
return 2 + rec(i+1, j-1)
else:
return max(rec(i+1, j), rec(i, j-1))
return rec(0, len(s)-1)
"""
#WRONG SOLUTIONS
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
def isPalin(s):
return s==s[::-1]
@lru_cache
def rec(i):
if i >= len(s):
return ""
else:
taken = s[i] + rec(i+1)
not_taken = rec(i+1)
if isPalin(taken) and isPalin(not_taken):
return taken if len(taken) > len(not_taken) else not_taken
elif isPalin(taken):
return taken
elif isPalin(not_taken):
return not_taken
else:
return s[i]
return rec(0)
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
def isPalin(s):
return s==s[::-1]
ans = 0
self.maxlen = 0
@lru_cache(None)
def rec(i, temp):
if isPalin(temp) and len(temp) > self.maxlen:
# print(temp)
self.maxlen = len(temp)
if i >= len(s):
return
else:
for j in range(i, len(s)):
temp += s[j]
# print(temp)
rec(j+1, temp)
temp = temp[:-1]
rec(0, "")
return self.maxlen
"""