1
class Solution {
2
public:
3
int countPalindromicSubsequence(string s) {
4
vector<pair<int, int>> v(26, {-1, -1}); // to store first occurance and
5
// last occurance of every alphabet.
6

7
int n = s.length(); // size of the string
8

9
for (int i = 0; i < n; i++) {
10
if (v[s[i] - 'a'].first == -1)
11
v[s[i] - 'a'].first = i; // storing when alphabet appered first time.
12
else
13
v[s[i] - 'a'].second = i; // else whenever it appears again. So that the
14
// last occurrence will be stored at last.
15
}
16

17
int ans = 0;
18
for (int i = 0; i < 26; i++) { // traversing over all alphabets.
19

20
if (v[i].second != -1) { // only if alphabet occured second time.
21

22
unordered_set<char> st; // using set to keep only unique elements between the range.
23

24
for (int x = v[i].first + 1; x < v[i].second; x++)
25
st.insert(s[x]); // set keeps only unique elemets.
26

27
ans += ((int)st.size()); // adding number of unique elements to the answer.
28
}
29
}
30
return ans;
31
}
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0