LeetCode 1371: Find the Longest Substring Containing Vowels in Even Counts Solution

Master LeetCode problem 1371 (Find the Longest Substring Containing Vowels in Even Counts), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1371. Find the Longest Substring Containing Vowels in Even Counts

Problem Explanation

Explanation:

To solve this problem, we can use a hashmap to keep track of the count of each vowel (a, e, i, o, u) seen so far in the string. We will initialize the hashmap with all vowels having a count of 0. As we traverse the string, we update the counts based on the vowels encountered and calculate the length of the substring where all vowels appear an even number of times.

We will use a bitmask to represent the count of each vowel in the substring. If a vowel appears even times, the corresponding bit in the bitmask will be 0, otherwise 1. We will store the bitmask in a hashmap along with the index where the bitmask was first encountered. At each index, we check if the current bitmask has been seen before. If yes, we update the result with the maximum substring length. :

Solution Code

class Solution {
    public int findTheLongestSubstring(String s) {
        int n = s.length();
        int ans = 0, state = 0;
        Map<Integer, Integer> seen = new HashMap<>();
        seen.put(0, -1);
        Map<Character, Integer> vowels = new HashMap<>();
        vowels.put('a', 1);
        vowels.put('e', 2);
        vowels.put('i', 4);
        vowels.put('o', 8);
        vowels.put('u', 16);

        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (vowels.containsKey(c)) {
                state ^= vowels.get(c);
            }
            seen.putIfAbsent(state, i);
            ans = Math.max(ans, i - seen.get(state));
        }
        return ans;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1371 (Find the Longest Substring Containing Vowels in Even Counts)?

This page provides optimized solutions for LeetCode problem 1371 (Find the Longest Substring Containing Vowels in Even Counts) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1371 (Find the Longest Substring Containing Vowels in Even Counts)?

The time complexity for LeetCode 1371 (Find the Longest Substring Containing Vowels in Even Counts) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1371 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1371 in Java, C++, or Python.

Back to LeetCode Solutions