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);
- // example 1 : result = 3
- result = MaxVowels("aeiou", 2);
- // example 2 : result = 2
- result = MaxVowels("leetcode", 3);
- // example 3 : result = 2
- result = MaxVowels("rhythms", 4);
- // example 4 : result = 0
- result = MaxVowels("tryhard", 4);
- // example 5 : result = 1
- }
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;
- }

Sachin JawalePosted Jan 27, 2021, 5:29 AM
Class Program { static void Main(string[] args) { // Basic Test Q1 Console.WriteLine(Q1("caberqiitefg", 5)); Console.WriteLine(Q1("aeiouia", 3)); Console.WriteLine(Q1("azerdii", 5)); Console.ReadLine(); } private static string Q1(string s, int k) { if (s.Count(x => "aieou".Contains(x)) == 0) return "Not found!"; int maxVowels = 0; string substringWithMaxVowels = string.Empty; for (int j = 0; j < s.Length; j++) { if (j + k > s.Length) break; int vowelsInSubstring = s.Substring(j, k).Count(c => "aieou".Contains(c)); if (vowelsInSubstring > maxVowels) { maxVowels = vowelsInSubstring; substringWithMaxVowels = s.Substring(j, k); } } return substringWithMaxVowels; } }