[LeetCode] Unique Length-3 Palindromic Subsequences

1930. Unique Length-3 Palindromic Subsequences

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”.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int countPalindromicSubsequence(string s) {
int n = s.length(), res = 0;
vector<pair<int, int>> fe(26, {INT_MAX - 1, INT_MIN});
for(int i = 0; i < n; i++) {
fe[s[i]-'a'].first = min(fe[s[i]-'a'].first, i);
fe[s[i]-'a'].second = max(fe[s[i]-'a'].second, i);
}
for(int i = 0; i < 26; i++) {
auto [f, e] = fe[i];
int mask = 0;
for(int j = f + 1; j < e; j++) {
mask |= 1<<(s[j] - 'a');
}
res += __builtin_popcount(mask);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/13/PS/LeetCode/unique-length-3-palindromic-subsequences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.