Статья пока доступна только на английском.
Problem Description
You are given a string s and a substring length k.
Write a function that returns the maximum number of vowels in any substring of s of length k.
Constraints
- The string length is from 1 to 100000
- The string consists only of lowercase English letters
- The substring length is in the range from 1 to the length of
s
Examples
Input
s = "abciiidef"
k = 3Answer: 3
The string contains a substring of length 3 consisting only of vowels: iii
Solution
This problem is a textbook example of the sliding window technique:
- We create a window of length
k(initially the left bound of the window is0and the right one isk-1) - We move the window by incrementing both the left and right indices by 1 on each step
- We count how many vowels fall into the window on each step
So first we count the vowels in the substring from element 0 to k-1 and store that as an intermediate result.
Then we start moving the window. To avoid recounting the vowels every time, we only look at what changed:
- If the new right element of the window is a vowel, the vowel count increases by one compared to the previous window, since the new substring includes an extra vowel.
- If the old left element of the window is a vowel, the vowel count decreases by one compared to the previous window, since we've excluded a vowel from the substring.
To speed things up, don't forget about early exit: if at some step we find a substring of length k made only of vowels, there's no need to analyze the rest of the string.
const isVowel = (char: string): boolean => {
switch (char) {
case 'a':
return true;
case 'e':
return true;
case 'i':
return true;
case 'o':
return true;
case 'u':
return true;
}
return false;
};
export const maxVowels = (s: string, k: number): number => {
let vowelsCount = 0;
for (let rightIdx = 0; rightIdx < s.length && rightIdx < k; rightIdx++) {
if (isVowel(s[rightIdx])) {
vowelsCount++;
}
}
if (vowelsCount == k) {
return vowelsCount;
}
let currentVowelsCount = vowelsCount;
let leftIdx = 0;
for (let rightIdx = k; rightIdx < s.length; rightIdx++) {
if (isVowel(s[rightIdx])) {
currentVowelsCount++;
}
if (isVowel(s[leftIdx])) {
currentVowelsCount--;
}
leftIdx++;
if (currentVowelsCount > vowelsCount) {
vowelsCount = currentVowelsCount;
if (vowelsCount == k) {
return vowelsCount;
}
}
}
return vowelsCount;
};Complexity Analysis
n is the number of characters in the string.
Time Complexity
O(n), since we're guaranteed to find the answer after going through the whole string once.
Space Complexity
O(1).