LeetCode 1371. Find the Longest Substring Containing Vowels in Even Counts Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1371. Find the Longest Substring Containing Vowels in Even Counts

Description

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.

Solutions

Solution 1: Prefix XOR + Array or Hash Table

According to the problem description, if we use a number to represent the parity of the occurrences of each vowel in a prefix of the string s, then when two prefixes have the same number, the substring between these two prefixes is a valid substring.

We can use the lower five bits of a binary number to represent the parity of the five vowels, where the i-th bit being 1 means the vowel appears an odd number of times in the substring, and 0 means it appears an even number of times.

We use mask to represent this binary number and use an array or hash table d to record the first occurrence of each mask. Initially, we set d[0] = -1, indicating that the start position of the empty string is -1.

We traverse the string s, and if we encounter a vowel, we toggle the corresponding bit in mask. Next, we check if mask has appeared before. If it has, we have found a valid substring, and its length is the current position minus the last occurrence of mask. Otherwise, we store the current position of mask in d.

After traversing the string, we will have found the longest valid substring.

The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).

PythonJavaC++GoTypeScript
class Solution: def findTheLongestSubstring(self, s: str) -> int: d = {0: -1} ans = mask = 0 for i, c in enumerate(s): if c in "aeiou": mask ^= 1 << (ord(c) - ord("a")) if mask in d: j = d[mask] ans = max(ans, i - j) else: d[mask] = i return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !