Description
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.
分析
题目的意思是:给定字符串s,找出一个最长字符串,使得字符串中的元音字符都是偶数个。这道题用bitmask,中文翻译应该是位掩码,就是把元音字符用一个数做位运算表示,由于我们只关心每个字符的奇偶,所以用异或很容易实现。然后用字典存储每个字符最早出现的位置,最后进行计算更新res。当前计算的mask为n,然后看字典汇总是否出现n,这样相减类似于
Even - Even = Even; Odd - Odd = even;
得到的都是偶数元音字符串,这样维护最长的res就是最终的结果了。
如果还没搞懂,就看看下面字典的变化,字典记录的事每个元音字母最早出现的位置,其中6是元音字母e和i最早出现的位置,依次类推,下面由我写的代码,可以打印中间值理解一下哈哈哈。
{0: -1, 2: 0}
{0: -1, 2: 0}
{0: -1, 2: 0}
{0: -1, 2: 0}
{0: -1, 2: 0}
{0: -1, 2: 0}
{0: -1, 2: 0, 6: 6}
{0: -1, 2: 0, 6: 6}
{0: -1, 2: 0, 6: 6}
{0: -1, 2: 0, 6: 6}
{0: -1, 2: 0, 6: 6, 10: 10}
{0: -1, 2: 0, 6: 6, 10: 10}
{0: -1, 2: 0, 6: 6, 10: 10}
{0: -1, 2: 0, 6: 6, 10: 10}
{0: -1, 2: 0, 6: 6, 10: 10}
{0: -1, 2: 0, 6: 6, 10: 10, 8: 15}
{0: -1, 2: 0, 6: 6, 10: 10, 8: 15}
代码
class Solution:
def findTheLongestSubstring(self, s: str) -> int:
vowels={'a':1,'e':2,'i':4,'o':8,'u':16}
n=0
d={0:-1}
res=0
for i,ch in enumerate(s):
if(ch in vowels):
n^=vowels[ch]
if(n not in d):
d[n]=i
else:
res=max(res,i-d[n])
return res
代码二
class Solution:
def findTheLongestSubstring(self, s: str):
vowels={'a':1,'e':2,'i':4,'o':8,'u':16}
n=0
d={0:-1}
res=0
for i,ch in enumerate(s):
if(ch in vowels):
n^=vowels[ch]
if(n not in d):
d[n]=i
else:
res=max(res,i-d[n])
print(d)
return res
if __name__ == "__main__":
solution=Solution()
s='eleetminicoworoep'
res=solution.findTheLongestSubstring(s)
print(res)
参考文献
[LeetCode] [Python] solution in O(n) time and O(1) space explained