LeetCode1371. 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.

二、题解

class Solution {
public:
    int findTheLongestSubstring(string s) {
        int n = s.size();
        vector<int> map(32,-2);
        map[0] = -1;
        int res = 0,status = 0;
        for(int i = 0;i < n;i++){
            int m = move(s[i]);
            if(m != -1) status ^= (1 << m);
            if(map[status] != -2) res = max(res,i - map[status]);
            else map[status] = i;
        }
        return res;
    }
    int move(char c){
        switch(c){
            case 'a' : return 0;
            case 'e' : return 1;
            case 'i' : return 2;
            case 'o' : return 3;
            case 'u' : return 4;
            default : return -1;
        }
    }
};

你可能感兴趣的:(算法,数据结构,c++,leetcode)