LeetCode1371. 每个元音包含偶数次的最长子字符串 [Medium]

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.

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

思路:参考votrubac。用 cur 来表示 s[0..i] 中各元音字符数的奇偶状况, cur 的初始值为 0b00000 ,每个二进制位对应元音字符是奇数还是偶数,当遇到了元音字符, cur 对应的二进制位进行反转,因此共有32种可能。如果 s[0..i]s[0...j] 对应的掩码 cur 相同,那么我们知道 s[i+1,...j] 中的元音数肯定为偶数。因此对于每个掩码值 cur ,我们只记录其最早出现的位置。注意对于掩码值 0b00000 ,我们并不修改其对应的首次出现的位置。

LeetCode1371. 每个元音包含偶数次的最长子字符串 [Medium]_第1张图片

工程代码下载

class Solution {
     
public:
    int findTheLongestSubstring(string s) {
     
        vector<int> m(32, -1);
        int res = 0, cur = 0;
        const string vowels = "aeiou";

        for(int i = 0; i < s.size(); ++i){
     
            size_t pos = vowels.find(s[i]);
            if(pos != string::npos){
     
                cur ^= 1 << pos;
                if(cur != 0 && m[cur] == -1)
                    m[cur] = i;
            }
            res = max(res, i - m[cur]);
        }

        return res;
    }
};

你可能感兴趣的:(leetcode)