[LeetCode] 1456. Maximum Number of Vowels in a Substring of Given Length

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:
Input: s = “abciiidef”, k = 3
Output: 3
Explanation: The substring “iii” contains 3 vowel letters.

Example 2:
Input: s = “aeiou”, k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.

Example 3:
Input: s = “leetcode”, k = 3
Output: 2
Explanation: “lee”, “eet” and “ode” contain 2 vowels.

Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
1 <= k <= s.length

定长子串中元音的最大数目。

给你字符串 s 和整数 k 。

请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。

英文中的 元音字母 为(a, e, i, o, u)。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-number-of-vowels-in-a-substring-of-given-length
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

思路是滑动窗口。这是一道窗口 size 固定的滑动窗口题。首先我们计算前 k 个字母中元音字母的个数,然后遍历之后剩下的所有字母,如果在滑动窗口右侧遇到的字母是元音,则 + 1,如果在滑动窗口左侧遇到的字母是元音,则 -1,因为他已经不在窗口范围内了。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public int maxVowels(String s, int k) {
int count = 0;
for (int i = 0; i < k; i++) {
char c = s.charAt(i);
if (helper(c)) {
count++;
}
}

int res = count;
for (int i = k; i < s.length(); i++) {
char c1 = s.charAt(i);
char c2 = s.charAt(i - k);
if (helper(c1)) {
count++;
}
if (helper(c2)) {
count--;
}
res = Math.max(res, count);
}
return res;
}

private boolean helper(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}

[LeetCode] 1456. Maximum Number of Vowels in a Substring of Given Length
https://shurui91.github.io/posts/1765365781.html
Author
Aaron Liu
Posted on
May 6, 2023
Licensed under