1456. Maximum Number of Vowels in a Substring of Given Length - Medium
前往題目
想法
- 雙指針,
sliding window
思路
- 左右指針
- 每個循環都檢查右指針的字是不是母音
- 是的話增加
count
- 超出
k
時縮短窗口 - 更新最大
count
Code
class Solution {
public int maxVowels(String s, int k) {
int l = 0;
int count = 0, res = 0; // count of the vowels and the final result
Set<Character> vowel = new HashSet();
vowel.add('a');
vowel.add('e');
vowel.add('i');
vowel.add('o');
vowel.add('u');
for (int r = 0; r < s.length(); ++r) {
// Check if vowel, increase count
char cur = s.charAt(r);
if (vowel.contains(cur)) {
++count;
}
// Shrink to a valid window
if (r - l + 1 > k) {
if (vowel.contains(s.charAt(l))) {
--count;
}
++l;
}
// Update the max length
res = Math.max(res, count);
}
return res;
}
}
1456. Maximum Number of Vowels in a Substring of Given Length - Medium
https://f88083.github.io/2024/07/18/1456-Maximum-Number-of-Vowels-in-a-Substring-of-Given-Length/