Leet Code Daily - 2024-04-30 - Number of Wonderful Substrings
Solution
Preffix Sum + Bit Mask.
Code
class Solution {
public:
int flip(int mask, int pos) {
int bit = 1 << pos;
return (mask & bit) ? (mask - bit) : (mask + bit);
}
long long wonderfulSubstrings(string word) {
long long cnt[1024] = { 1, 0 }, ans = 0;
int mask = 0;
for (const char& c : word) {
mask = flip(mask, c - 'a');
ans += cnt[mask];
for (char c = 'a'; c <= 'j'; c++) {
ans += cnt[flip(mask, c - 'a')];
}
cnt[mask]++;
}
return ans;
}
};