← All problems

1371. Find the Longest Substring Containing Vowels in Even Counts

MediumOpen on LeetCodeProblem statement

Problem Statement

1371. Find the Longest Substring Containing Vowels in Even Counts

Medium


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:

Java — brute force

Source file
class Solution {
    public int findTheLongestSubstring(String s) {
        int as = 0, es = 0, is = 0, os = 0, us = 0;
        for (int i=0; i<s.length(); i++) {
            switch (s.charAt(i)) {
                case 'a' -> as++;
                case 'e' -> es++;
                case 'i' -> is++;
                case 'o' -> os++;
                case 'u' -> us++;
            }
        }

        if (as % 2 == 0 && es % 2 == 0 && is % 2 == 0 && os % 2 == 0 && us % 2 == 0) {
            return s.length();
        }

        int left = 0;
        int right = s.length();
        boolean nextLeft = false;
        while (right - left > 0) {
            char removed = nextLeft ? s.charAt(left++) : s.charAt(right-- - 1);
            switch (removed) {
                case 'a' -> as--;
                case 'e' -> es--;
                case 'i' -> is--;
                case 'o' -> os--;
                case 'u' -> us--;
            }

            if (as % 2 == 0 && es % 2 == 0 && is % 2 == 0 && os % 2 == 0 && us % 2 == 0) {
                return right - left;
            }

            for (int i = 0; i < s.length() - (right - left); i++) {
                removed = nextLeft ? s.charAt(right-- - 1) : s.charAt(left ++);
                char added = nextLeft ? s.charAt(--left) : s.charAt(++right - 1);
                switch (removed) {
                    case 'a' -> as--;
                    case 'e' -> es--;
                    case 'i' -> is--;
                    case 'o' -> os--;
                    case 'u' -> us--;
                }
                switch (added) {
                    case 'a' -> as++;
                    case 'e' -> es++;
                    case 'i' -> is++;
                    case 'o' -> os++;
                    case 'u' -> us++;
                }

                if (as % 2 == 0 && es % 2 == 0 && is % 2 == 0 && os % 2 == 0 && us % 2 == 0) {
                    return right - left;
                }
            }
            nextLeft = !nextLeft;
        }

        return 0;
    }
}