Introduction
Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Note that vowel letters in English are [ a, e, i, o, u ]. So let's take an example where s is "abciiidef" and k is 3. so the output will be 3 because the substring "iii" contains 3 vowel letters in the string s. Given below are some more examples:
- static void Main(string[] args)
- {
- var result = MaxVowels("abciiidef", 3);
-
- result = MaxVowels("aeiou", 2);
-
- result = MaxVowels("leetcode", 3);
-
- result = MaxVowels("rhythms", 4);
-
- result = MaxVowels("tryhard", 4);
-
- }
Solution
Our approach towards the problem will be simplest, we will have nested loops one which will substring the string s and the next will count the vowels in that substring. Here are the steps to how it's done,
- Create a list of vowels for reference and assign [ a, e, i, o, u ].
- Iterate from 0th to (s.Length - k)th index of the string s to get all the substrings of length k.
- Count the vowels for every substring.
- Compare every vowel count of substrings and return the maximum vowel count.
Here is the C# code for the algorithm given above:
- public static int MaxVowels(string s, int k)
- {
- int maxVowels = 0;
- List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' };
- for (int i = 0; i <= s.Length - k; i++)
- {
- string substring = s.Substring(i, k);
- int countVowels = substring.Where(x => vowels.Contains(x)).Count();
- maxVowels = Math.Max(countVowels, maxVowels);
- }
- return maxVowels;
- }