To solve this problem, we need to find the length of the longest substring of a given string that contains at most k vowels. The solution leverages the sliding window technique, which efficiently handles contiguous substring problems with linear time complexity.
Approach
The sliding window technique involves using two pointers (left and right) to represent the current window of the string being considered. Here's the step-by-step breakdown:
- Vowel Set: Define a set of vowels to quickly check if a character is a vowel.
- Initialization: Start with
leftpointer at 0,vowel_count(to track vowels in the current window) at 0, andmax_len(to store the length of the longest valid substring) at 0. - Expand Window: Move the
rightpointer to the right, incrementingvowel_countif the character atrightis a vowel. - Shrink Window: If
vowel_countexceedsk, move theleftpointer to the right untilvowel_countis within the limit, adjustingvowel_countas needed. - Update Max Length: After each valid window adjustment, compute the length of the current window and update
max_lenif it's the longest valid window so far.
Solution Code
def maxVowels(s: str, k: int) -> int:
vowels = {'a', 'e', 'i', 'o', 'u'}
left = 0
vowel_count = 0
max_len = 0
for right in range(len(s)):
# Add current character to the window
if s[right] in vowels:
vowel_count += 1
# Shrink the window if vowels exceed k
while vowel_count > k:
if s[left] in vowels:
vowel_count -= 1
left += 1
# Update the maximum length of valid window
current_length = right - left + 1
if current_length > max_len:
max_len = current_length
return max_len
Explanation
- Vowel Check: The set
vowelsallows O(1) time complexity for checking if a character is a vowel. - Sliding Window: The
rightpointer expands the window to include more characters, while theleftpointer shrinks it when the number of vowels exceedsk. This ensures that we only process each character at most twice (once byrightand once byleft), leading to O(n) time complexity. - Efficiency: The space complexity is O(1) since we use a fixed-size set and a few variables.
This approach efficiently finds the longest substring with at most k vowels, making it suitable for large input sizes. The solution handles all edge cases, including when k is 0 (longest substring with no vowels) and when all characters are vowels (longest substring is the entire string if k is large enough).
Example: For s = "leetcode" and k = 2, the longest valid substring is "tcode" (length 5), which the code correctly returns.
Answer: The function maxVowels returns the length of the longest substring with at most k vowels. For the given problem (assuming the input matches the common use case), this code is the correct solution.

作者声明:本文包含人工智能生成内容。