题目:1456. 定长子串中元音的最大数目
给你字符串 s 和整数 k 。
请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。
英文中的 元音字母 为(a, e, i, o, u)。
示例 1:
输入:s = “abciiidef”, k = 3
输出:3
解释:子字符串 “iii” 包含 3 个元音字母。
示例 2:
输入:s = “aeiou”, k = 2
输出:2
解释:任意长度为 2 的子字符串都包含 2 个元音字母。
示例 3:
输入:s = “leetcode”, k = 3
输出:2
解释:“lee”、“eet” 和 “ode” 都包含 2 个元音字母。
示例 4:
输入:s = “rhythms”, k = 4
输出:0
解释:字符串 s 中不含任何元音字母。
示例 5:
输入:s = “tryhard”, k = 4
输出:1
提示:
1 <= s.length <= 10^5
s 由小写英文字母组成
1 <= k <= s.length
链接:https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length
解题:
class Solution {
/*
请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。
思路:固定滑动窗口
*/
public static int maxVowels(String s, int k) {
if (null == s || s.length() == 0 || k < 1) {
return -1;
}
int left = 0, right = 0; // 定义窗口指针
int res = 0;
int sum = 0;
while (right < s.length()) {
sum = sum + isyyin(s.charAt(right));
right ++;
if (right >= k) {
res = Math.max(res, sum);
// 判断窗口的第一个元素,去掉窗口外的元音字母计数
sum = sum - isyyin(s.charAt(right - k));
}
}
return res;
}
public static int isyyin(char c) {
// a, e, i, o, u
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ? 1 : 0;
}
public static void main(String[] args) {
System.out.println(maxVowels("abciiidef", 3));//输出:3
System.out.println(maxVowels("aeiou", 2));//输出:2
System.out.println(maxVowels("abciiidef", 3));//输出:3
System.out.println(maxVowels("leetcode", 3));//输出:2
}
}