Number of Wonderful Substrings LeetCode solution in Java

1
class Solution {
2
public long wonderfulSubstrings(String word) {
3
int n = word.length();
4
long count = 0;
5

6
long[] freq =
7
new long
8
[(1 << 10) + 1]; // Since we have to take only 2^10 possibilies, we can avoid an HashMap
9

10
freq[0] = 1;
11
int res =
12
0; // initialize the frequency of 0000000000 as 1 because when no element is encountered,
13
// then th bitmask is 0
14

15
for (int i = 0; i < n; i++) {
16
int mask = (1 << (word.charAt(i) - 'a'));
17
res ^=
18
mask; // toggling bit of the current character to make it from odd to even OR even to odd
19
int chkMask = 1;
20

21
count += freq[res];
22
for (int j = 1;
23
j <= 10;
24
j++) { // Loop for checking all possiblities of different places of the Different Bit
25
count += freq[chkMask ^ res];
26
chkMask <<= 1;
27
}
28

29
freq[res]++; // increasing the frequency of the current bitmask
30
}
31

32
return count;
33
}
34
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0