[LeetCode] Find the Longest Substring Containing Vowels in Even Counts

1371. Find the Longest Substring Containing Vowels in Even Counts

Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ must appear an even number of times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int findTheLongestSubstring(string s) {
auto bit = [](char ch) {
if(ch == 'a') return 0;
if(ch == 'e') return 1;
if(ch == 'i') return 2;
if(ch == 'o') return 3;
if(ch == 'u') return 4;
return -1;
};
unordered_map<int, int> mp;
mp[0] = -1;
int res = 0;
for(int i = 0, mask = 0; i < s.length(); i++) {
int bi = bit(s[i]);
if(bi != -1) mask ^= (1<<bi);
if(mp.count(mask)) {
res = max(res, i - mp[mask]);
} else mp[mask] = i;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/07/PS/LeetCode/find-the-longest-substring-containing-vowels-in-even-counts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.