[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 class Solution { 2 public int maxVowels(String s, int k) { 3 int count = 0; 4 for (int i = 0; i < k; i++) { 5 char c = s.charAt(i); 6 if (helper(c)) { 7 count++; 8 } 9 } 10 11 int max = count; 12 for (int i = k; i < s.length(); i++) { 13 if (helper(s.charAt(i))) { 14 count++; 15 } 16 if (helper(s.charAt(i - k))) { 17 count--; 18 } 19 max = Math.max(max, count); 20 } 21 return max; 22 } 23 24 private boolean helper(char c) { 25 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; 26 } 27 }