Find the Longest Substring Containing Vowels in Even Counts LeetCode solution in JavaScript

1
var findTheLongestSubstring = function (s) {
2
// u o i e a
3
// 0 0 0 0 0 => initial state, all are even letters
4
// s = "abcab"
5
// 0 0 0 0 1 => at index 0, only a is odd count
6
// 0 0 0 0 1 => at index 1, max = 1
7
// 0 0 0 0 1 => at index 2, max = 2
8
// 0 0 0 0 0 => at index 3, max = 4
9
// 0 0 0 0 0 => at index 4, max = 5
10

11
// valid condition: same state in previous index, then it means we have a even count for all letters within the middle substring.
12
var mask = 0;
13
var t = "aeiou";
14
var count = new Map(); // <mask, first_idx>
15
count.set(0, -1);
16
var res = 0;
17
for (var i = 0; i < s.length; i++) {
18
if (t.indexOf(s[i]) >= 0) {
19
var j = t.indexOf(s[i]);
20
mask = mask ^ (1 << j);
21
}
22
if (!count.has(mask)) {
23
count.set(mask, i);
24
} else {
25
// substring is from [prevIdx+1, i];
26
res = Math.max(res, i - count.get(mask));
27
}
28
}
29
return res;
30
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0