Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1456. Maximum Number of Vowels in a Substring of Given Length

StringSliding Window

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:

  1. Initialize variables maxVowels and curVowels to track the maximum number of vowels and current number of vowels in the window respectively.
  2. Iterate through the first k characters of the string s and count the number of vowels in this initial window.
  3. Update maxVowels with the count of vowels in the initial window.
  4. Slide the window by removing the leftmost character and adding the next character in the string.
  5. 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.
  6. Update maxVowels if the count of vowels in the current window is greater than maxVowels.
  7. Repeat steps 4-6 until the end of the string is reached.
  8. 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.