To find the maximum number of vowels in any substring of length k, we can use a sliding window of size k and count the vowels as the window moves. This allows us to efficiently update the count without re-scanning the whole substring each time.
classSolution {
public:int maxVowels(string s, int k) {
auto isVowel = [](char c) {
return c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u';
};
int cnt =0, ans =0, n = s.size();
for (int i =0; i < n; ++i) {
if (isVowel(s[i])) cnt++;
if (i >= k && isVowel(s[i - k])) cnt--;
ans = max(ans, cnt);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
funcmaxVowels(sstring, kint) int {
isVowel:=func(cbyte) bool {
returnc=='a'||c=='e'||c=='i'||c=='o'||c=='u' }
cnt, ans:=0, 0fori:=0; i < len(s); i++ {
ifisVowel(s[i]) {
cnt++ }
ifi>=k&&isVowel(s[i-k]) {
cnt-- }
ifcnt > ans {
ans = cnt }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintmaxVowels(String s, int k) {
int cnt = 0, ans = 0, n = s.length();
for (int i = 0; i < n; i++) {
if (isVowel(s.charAt(i))) cnt++;
if (i >= k && isVowel(s.charAt(i - k))) cnt--;
ans = Math.max(ans, cnt);
}
return ans;
}
privatebooleanisVowel(char c) {
return c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaxVowels(s: String, k: Int): Int {
funisVowel(c: Char) = c in"aeiou"var cnt = 0var ans = 0for (i in s.indices) {
if (isVowel(s[i])) cnt++if (i >= k && isVowel(s[i - k])) cnt-- ans = maxOf(ans, cnt)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaxVowels(self, s: str, k: int) -> int:
vowels = set('aeiou')
cnt = ans =0for i, c in enumerate(s):
if c in vowels:
cnt +=1if i >= k and s[i - k] in vowels:
cnt -=1 ans = max(ans, cnt)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmax_vowels(s: String, k: i32) -> i32 {
let s = s.as_bytes();
letmut cnt =0;
letmut ans =0;
for i in0..s.len() {
ifb"aeiou".contains(&s[i]) {
cnt +=1;
}
if i asi32>= k &&b"aeiou".contains(&s[i - k asusize]) {
cnt -=1;
}
ans = ans.max(cnt);
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
maxVowels(s: string, k: number):number {
constvowels=newSet(['a','e','i','o','u']);
letcnt=0, ans=0;
for (leti=0; i<s.length; i++) {
if (vowels.has(s[i])) cnt++;
if (i>=k&&vowels.has(s[i-k])) cnt--;
ans= Math.max(ans, cnt);
}
returnans;
}
}