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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2015-10-08 Interview with BOA