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.
- For example,
"ace"
is a subsequence of"abcde"
.
Example 1:
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:
Input: s = "adc" Output: 0 Explanation: There are no palindromic subsequences of length 3 in "adc".
Example 3:
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:
3 <= s.length <= 105
s
consists of only lowercase English letters.
class Solution:
def countPalindromicSubsequence(self, s: str) -> int:
res = 0
for i in range(26):
c = chr(ord('a') + i)
if c in s:
l, r = s.index(c), s.rindex(c)
chars = {s[j] for j in range(l + 1, r)}
res += len(chars)
return res
class Solution {
public int countPalindromicSubsequence(String s) {
int res = 0;
for (char c = 'a'; c <= 'z'; ++c) {
int l = s.indexOf(c), r = s.lastIndexOf(c);
Set<Character> chars = new HashSet<>();
for (int i = l + 1; i < r; ++i) {
chars.add(s.charAt(i));
}
res += chars.size();
}
return res;
}
}
class Solution {
public:
int countPalindromicSubsequence(string s) {
int res = 0;
for (char c = 'a'; c <= 'z'; ++c) {
int l = s.find_first_of(c), r = s.find_last_of(c);
unordered_set<char> chars;
for (int i = l + 1; i < r; ++i) {
chars.insert(s[i]);
}
res += chars.size();
}
return res;
}
};
func countPalindromicSubsequence(s string) int {
res := 0
for c := 'a'; c <= 'z'; c++ {
l, r := strings.Index(s, string(c)), strings.LastIndex(s, string(c))
chars := make(map[byte]bool)
for i := l + 1; i < r; i++ {
chars[s[i]] = true
}
res += len(chars)
}
return res
}