1456. Maximum Number of Vowels in a Substring of Given Length
Explanation:
To solve this problem, we can use a sliding window approach. We will iterate through the string s
with a window size of k
, counting the number of vowels in each window. We will keep track of the maximum number of vowels found in any window and return this maximum count at the end.
Here is the step-by-step algorithm:
- Initialize variables
maxVowels
andcurVowels
to track the maximum number of vowels and current number of vowels in the window respectively. - Iterate through the first
k
characters of the strings
and count the number of vowels in this initial window. - Update
maxVowels
with the count of vowels in the initial window. - Slide the window by removing the leftmost character and adding the next character in the string.
- Update the count of vowels in the window by subtracting the leftmost character if it was a vowel and adding the new character if it is a vowel.
- Update
maxVowels
if the count of vowels in the current window is greater thanmaxVowels
. - Repeat steps 4-6 until the end of the string is reached.
- Return the
maxVowels
found.
class Solution {
public int maxVowels(String s, int k) {
int maxVowels = 0;
int curVowels = 0;
String vowels = "aeiou";
for (int i = 0; i < k; i++) {
if (vowels.contains(String.valueOf(s.charAt(i)))) {
curVowels++;
}
}
maxVowels = curVowels;
for (int i = k; i < s.length(); i++) {
if (vowels.contains(String.valueOf(s.charAt(i - k)))) {
curVowels--;
}
if (vowels.contains(String.valueOf(s.charAt(i)))) {
curVowels++;
}
maxVowels = Math.max(maxVowels, curVowels);
}
return maxVowels;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.