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

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

Question

Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.

Vowel letters in English are 'a''e''i''o', and 'u'.

Solution

使用count记录元音数量,max记录元音的最大值。

遍历字符串,如果当前字符属于元音,则count++。

同时,如果移动出的字符是元音,则count–。

每次遍历结束更新max值。

最后返回max。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int maxVowels(String s, int k) {
int count = 0, max = Integer.MIN_VALUE;
for(int i = 0; i < s.length(); i++){
char curChar = s.charAt(i);
if(curChar == 'a' || curChar == 'e' || curChar == 'i' ||
curChar == 'o' || curChar == 'u') {
count++;
}
if(i >= k){
char lastChar = s.charAt(i - k);
if(lastChar == 'a' || lastChar == 'e' || lastChar == 'i' ||
lastChar == 'o' || lastChar == 'u'){
count--;
}

}
max = Math.max(max, count);
}
return max;
}
}
Author

Xander

Posted on

2023-05-05

Updated on

2023-05-08

Licensed under

Comments