LeetCode 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.
Example 1:
Input: s = "eleetminicoworoep" Output: 13 Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.
Example 2:
Input: s = "leetcodeisgreat" Output: 5 Explanation: The longest substring is "leetc" which contains two e's.
Example 3:
Input: s = "bcbcbc" Output: 6 Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.
Constraints:
1 <= s.length <= 5 x 10^5
s
contains only lowercase English letters.
题解:
We need to know if the vowel count is even. But we don't really need the count, we need to know count % 2 == 0.
Thus we could use ^.
We need a mask to maintain the current state.
We also need a map to maintain the state to its oldest index. If we see the same state, then it means this period from its oldest index has all the even vowels.
1 << (ind + 1) >> 1 since here if it is not vowek, ind is -1. 1<<0>>1 == 0. That is why we need ind + 1.
Time Complexity: O(n). n = s.length().
Space: O(1). At most 32 states.
AC Java:
1 class Solution { 2 public int findTheLongestSubstring(String s) { 3 String vow = "aeiou"; 4 int res = 0; 5 Map<Integer, Integer> hm = new HashMap<>(); 6 hm.put(0, -1); 7 int mask = 0; 8 int n = s.length(); 9 for(int i = 0; i < n; i++){ 10 char c = s.charAt(i); 11 int ind = vow.indexOf(c); 12 mask ^= 1 << (ind + 1) >> 1; 13 hm.putIfAbsent(mask, i); 14 res = Math.max(res, i - hm.get(mask)); 15 } 16 17 return res; 18 } 19 }