Open songyy5517 opened 6 months ago
Approach: Sliding Window
num
: the number of vowels in str[0:k-1]
;max = num
: the global maximum of vowels.max
.Complexity Analysis
class Solution {
public int maxVowels(String s, int k) {
// 思路:滑动窗口
// 1. 异常处理
if (s == null || s.length() < k)
return 0;
// 2. 变量定义
int sum = 0;
for (int i = 0; i < k; i++){
sum += isVowel(s.charAt(i));
}
int max_sum = sum;
// 3. 遍历字符串
for (int i = k; i < s.length(); i++){
sum = sum + isVowel(s.charAt(i)) - isVowel(s.charAt(i - k));
max_sum = Math.max(max_sum, sum);
}
return max_sum;
}
int isVowel(char c){
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ? 1 : 0;
}
}
2024/5/13
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'.
Example 1:
Example 2:
Example 3:
Intuition The problem is to find a substring of length k with the most vowels. So we need to check every substring of length k in the original string. Therefore, we can loop through the string with a sliding window. For each step, we calculate the number of vowels in the current substring and compare it with the global maximum.