Post

2059 Unique Length 3 Palindromic Subsequences

2059 Unique Length 3 Palindromic Subsequences

Unique Length-3 Palindromic Subsequences image

Given a string s, return *the number of unique palindromes of length three that are a subsequence of *s.

Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.

A palindrome is a string that reads the same forwards and backwards.

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.

1
For example, "ace" is a subsequence of "abcde".

 

Example 1:

1
2
3
4
5
6
7
8
**Input:** s = "aabca"
**Output:** 3
**Explanation:** The 3 palindromic subsequences of length 3 are:
- "aba" (subsequence of "aabca")
- "aaa" (subsequence of "aabca")
- "aca" (subsequence of "aabca")

Example 2:

1
2
3
4
5
**Input:** s = "adc"
**Output:** 0
**Explanation:** There are no palindromic subsequences of length 3 in "adc".

Example 3:

1
2
3
4
5
6
7
8
9
**Input:** s = "bbcbaba"
**Output:** 4
**Explanation:** The 4 palindromic subsequences of length 3 are:
- "bbb" (subsequence of "bbcbaba")
- "bcb" (subsequence of "bbcbaba")
- "bab" (subsequence of "bbcbaba")
- "aba" (subsequence of "bbcbaba")

 

Constraints:

1
2
3 <= s.length <= 105
s consists of only lowercase English letters.
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

class Solution:
    def countPalindromicSubsequence(self, s: str) -> int:
        arr = [(-1,-1)] * 26
        #suff.reverse()

        for idx, k in enumerate(s):
            if arr[ord(k) - ord('a')] == (-1,-1):
                arr[ord(k) - ord('a')] = (idx, -1)
            else:
                arr[ord(k) - ord('a')] = (arr[ord(k) - ord('a')][0], idx)
        # there may a problem of duplicates - will not  be
        res = 0
        for (k0, k1) in arr:
            if k0 >= 0 and k1 >= 0 and k1 > k0 + 1:
                st = set()
                for m in s[k0+1:k1]:
                    st.add(m)
                res += (len(st))
        return res



        



This post is licensed under CC BY 4.0 by the author.