1371. 每个元音包含偶数次的最长子字符串

2021/04/03 leetcode 共 781 字,约 3 分钟

title

problem link

给你一个字符串 s ,请你返回满足以下条件的最长子字符串的长度:每个元音字母,即 ‘a’,’e’,’i’,’o’,’u’ ,在子字符串中都恰好出现了偶数次。

示例 1:

输入:s = "eleetminicoworoep"
输出:13
解释:最长子字符串是 "leetminicowor" ,它包含 e,i,o 各 2 个,以及 0 个 a,u 。

示例 2:

输入:s = "leetcodeisgreat"
输出:5
解释:最长子字符串是 "leetc" ,其中包含 2 个 e 。

示例 3:

输入:s = "bcbcbc"
输出:6
解释:这个示例中,字符串 "bcbcbc" 本身就是最长的,因为所有的元音 a,e,i,o,u 都出现了 0 次。

提示:

  • 1 <= s.length <= 5 x 10^5
  • s 只包含小写英文字母。

solution

前缀和+hash表

可方便计算利用前缀和的第一次出现位置,就是hash存的第一次位置,用于求最长区间。,1371. 每个元音包含偶数次的最长子字符串

class Solution:
    def findTheLongestSubstring(self, s: str) -> int:
        if not s: return 0
        pos = {}
        ans = 0
        status = 0
        pos[0] = 0
        for i, c in enumerate(s):
            if c == "a":
                status ^= (1 << 1)
            elif c == "e":
                status ^= (1 << 2)
            elif c == "i":
                status ^= (1 << 3)
            elif c == "o":
                status ^= (1 << 4)
            elif c == "u":
                status ^= (1 << 5)
            print(bin(status))
            if status in pos:
                ans = max(ans, i+1 - pos[status])
            else:
                pos[status] = i+1
        return ans

Search

    Table of Contents