Skip to content

Commit 3814004

Browse files
Add files via upload
1 parent 451bd67 commit 3814004

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Medium
2+
# Topics
3+
# premium lock icon
4+
# Companies
5+
# Hint
6+
# Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
7+
8+
# Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
9+
10+
# A palindrome is a string that reads the same forwards and backwards.
11+
12+
# 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.
13+
14+
# For example, "ace" is a subsequence of "abcde".
15+
16+
17+
# Example 1:
18+
19+
# Input: s = "aabca"
20+
# Output: 3
21+
# Explanation: The 3 palindromic subsequences of length 3 are:
22+
# - "aba" (subsequence of "aabca")
23+
# - "aaa" (subsequence of "aabca")
24+
# - "aca" (subsequence of "aabca")
25+
# Example 2:
26+
27+
# Input: s = "adc"
28+
# Output: 0
29+
# Explanation: There are no palindromic subsequences of length 3 in "adc".
30+
# Example 3:
31+
32+
# Input: s = "bbcbaba"
33+
# Output: 4
34+
# Explanation: The 4 palindromic subsequences of length 3 are:
35+
# - "bbb" (subsequence of "bbcbaba")
36+
# - "bcb" (subsequence of "bbcbaba")
37+
# - "bab" (subsequence of "bbcbaba")
38+
39+
class Solution:
40+
def countPalindromicSubsequence(self, s: str) -> int:
41+
first = {}
42+
last = {}
43+
for i, ch in enumerate(s):
44+
if ch not in first:
45+
first[ch] = i
46+
last[ch] = i
47+
48+
result = 0
49+
50+
# Step 2: for each character, check possible middle chars
51+
for ch in set(s):
52+
if first[ch] < last[ch]: # must have at least 2 occurrences
53+
middle_chars = set(s[first[ch] + 1 : last[ch]])
54+
result += len(middle_chars)
55+
56+
return result
57+
58+

0 commit comments

Comments
 (0)