1371. Find the Longest Substring Containing Vowels in Even Counts #542
-
Topics: Given the string Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use bit manipulation to track the parity (even or odd) of vowels, along with a hash table to store prefix states. Here's how it can be approached: Steps:
Let's implement this solution in PHP: 1371. Find the Longest Substring Containing Vowels in Even Counts <?php
/**
* @param String $s
* @return Integer
*/
function findTheLongestSubstring($s) {
$n = strlen($s);
$mask = 0; // Initialize the bitmask
$longest = 0; // This will store the longest valid substring length
$vowels = ['a' => 0, 'e' => 1, 'i' => 2, 'o' => 3, 'u' => 4];
// Initialize the hash table to store the first occurrence of each bitmask
// At mask = 0 (start), we have already seen it at index -1 (before any characters)
$mask_position = array();
$mask_position[0] = -1;
for ($i = 0; $i < $n; $i++) {
$ch = $s[$i];
// If the character is a vowel, flip its corresponding bit in the bitmask
if (isset($vowels[$ch])) {
$mask ^= (1 << $vowels[$ch]);
}
// Check if this bitmask has been seen before
if (isset($mask_position[$mask])) {
// Calculate the length of the substring from the previous occurrence
$longest = max($longest, $i - $mask_position[$mask]);
} else {
// Record the first time this bitmask is encountered
$mask_position[$mask] = $i;
}
}
return $longest;
}
// Test cases
echo findTheLongestSubstring("eleetminicoworoep") . "\n"; // Output: 13
echo findTheLongestSubstring("leetcodeisgreat") . "\n"; // Output: 5
echo findTheLongestSubstring("bcbcbc") . "\n"; // Output: 6
?> Explanation:
Time Complexity:
Example Walkthrough:For the input
For the input
For the input
|
Beta Was this translation helpful? Give feedback.
We can use bit manipulation to track the parity (even or odd) of vowels, along with a hash table to store prefix states. Here's how it can be approached:
Steps:
Bitmask Representation: Since there are five vowels (
a, e, i, o, u
), we can use a 5-bit integer (bitmask) to represent whether the count of each vowel is odd or even. For each character:0
represents whether the count of 'a' is odd.1
represents whether the count of 'e' is odd.2
represents whether the count of 'i' is odd.3
represents whether the count of 'o' is odd.4
represents whether the count of 'u' is odd.For example, a bitmask
00110
meansi
ando
appear an odd number of times, whilea
,e
, andu
app…