[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 |
|