-
Notifications
You must be signed in to change notification settings - Fork 0
/
01930-unique-length-3-palindromic-subsequences.cpp
49 lines (44 loc) · 1.56 KB
/
01930-unique-length-3-palindromic-subsequences.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* medium :: hashmap */
/*
Create a map that takes a char and returns the first index and a possible later index.
If we can fit at least one char in between these indices there are subsequences.
We then add all unique chars in between those two indices to our returned integer.
Example:
string "aoba" => { 'a': { 0, 3 }, ... }
chars 'o' and 'b' will be encountered, add 2 to returned integer.
"aoa" and "aba"
- - - -
Time :: O(N) :: 164ms
Space :: O(N) :: 16.13MB
*/
class Solution {
public:
// Solution entrypoint :: - - - -
int countPalindromicSubsequence( string s )
{
const int32_t n = s.length();
int32_t ret = 0;
unordered_map<char, pair<int32_t, int32_t>> occ;
for ( int32_t i = 0; i < n; ++i )
{
// First occurence index :
if ( !occ.contains( s[i] ) ) {
occ[s[i]].first = i;
}
// Most recent :
occ[s[i]].second = i;
}
for ( auto& [chr, p] : occ )
{
// No valid space :
if ( p.second - p.first <= 1 ) { continue; }
unordered_set<char> chars;
for ( int32_t i = p.first + 1; i < p.second; ++i ) {
chars.insert( s[i] );
}
ret += chars.size();
}
return ret;
}
};
// End. :: - - - -