[leetcode] 1371. Find the Longest Substring Containing Vowels in Even Counts

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值