Skip to content

Commit cf7c783

Browse files
committed
Time: 514 ms (48.59%), Space: 18.4 MB (26.6%) - LeetHub
1 parent d7ae047 commit cf7c783

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# time complexity: O(n)
2+
# space complexity: O(1)
3+
4+
class Solution:
5+
def countPalindromicSubsequence(self, s: str) -> int:
6+
first = [-1] * 26
7+
last = [-1] * 26
8+
for i in range(len(s)):
9+
curr = ord(s[i]) - ord('a')
10+
if first[curr] == -1:
11+
first[curr] = i
12+
last[curr] = i
13+
14+
ans = 0
15+
for i in range(26):
16+
if first[i] == -1:
17+
continue
18+
between = set()
19+
for j in range(first[i] + 1, last[i]):
20+
between.add(s[j])
21+
ans += len(between)
22+
return ans
23+
24+
25+
s = "aabca"
26+
print(Solution().countPalindromicSubsequence(s))
27+
s = "adc"
28+
print(Solution().countPalindromicSubsequence(s))
29+
s = "bbcbaba"
30+
print(Solution().countPalindromicSubsequence(s))

0 commit comments

Comments
 (0)