DEV Community

Tanuja V
Tanuja V

Posted on • Updated on

Maximum Number of Vowels in a Substring of Given Length | LeetCode | Java

Algorithm

Sliding Window - It is an algorithm which slides at each iteration to give us the correct result.

class Solution {
    public int maxVowels(String s, int k) {

        Set<Character> set = new HashSet<>();

        set.add('a');
        set.add('e');
        set.add('i');
        set.add('o');
        set.add('u');


        char arr[] = s.toCharArray();

        int count = 0, maxCount = 0;

        for(int i=0; i<k; i++){
            if(set.contains(arr[i]))
                count++;
        }

        maxCount = count;

        int n = arr.length;

        for(int i=k; i<n; i++){
            if(set.contains(arr[i]))
                count++;
             if(set.contains(arr[i-k]))
                count--;

            maxCount = Math.max(count, maxCount);
        }

        return maxCount;

    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (0)