Try   HackMD

1456.Maximum Number of Vowels in a Substring of Given Length

tags: Medium,String,Sliding Window

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

解答

Python

class Solution: def maxVowels(self, s: str, k: int) -> int: vowels = 'aeiou' count = 0 for i in range(k): count += s[i] in vowels ans = count for i in range(k, len(s)): count -= s[i - k] in vowels count += s[i] in vowels ans = max(ans, count) return ans

Yen-Chi ChenFri, May 5, 2023

class Solution: def maxVowels(self, s: str, k: int) -> int: i, j = 0, 0 vowels = 'aeiou' max_length = 0 count_vowel = 0 while i < len(s) and j < len(s): if j - i < k: if s[j] in vowels: count_vowel += 1 max_length = max(max_length, count_vowel) j += 1 else: if s[i] in vowels: count_vowel -= 1 i += 1 return max_length

Ron ChenFri, May 5, 2023

TypeScript

function maxVowels(s: string, k: number): number { let max = 0; let currentMax = 0; const vowels = ['a', 'e', 'i', 'o', 'u']; const queue: string[] = []; for (let i = 0; i < s.length; i++) { if (queue.length < k) { if (vowels.includes(s[i])) currentMax++; queue.push(s[i]); } else { if (vowels.includes(queue.shift()!)) currentMax--; if (vowels.includes(s[i])) currentMax++; queue.push(s[i]); } if (currentMax > max) max = currentMax; } return max; }

學習了

function maxVowels(s: string, k: number): number { let max = 0; let currentMax = 0; const vowels = ['a', 'e', 'i', 'o', 'u']; for (let i = 0; i < s.length; i++) { if (i < k && vowels.includes(s[i])) { currentMax++; } else { if (vowels.includes(s[i])) currentMax++; if (vowels.includes(s[i - k])) currentMax--; } max = Math.max(max, currentMax); } return max; }

SheepFri, May 5, 2023

C#

public int MaxVowels(string s, int k) { string vowels = "aeiou"; int count = s.Take(k).Count(c => vowels.Contains(c)); int max = 0; for(int i = k; i < s.Length; i++) { if (vowels.Contains(s[i])) count++; if (vowels.Contains(s[i-k])) count--; max = Math.Max(max, count); } return max; }

JimFri, May 5, 2023

Javascript

function maxVowels(s, k) { const vowels = ['a', 'e', 'i', 'o', 'u']; let count = 0; for (let i = 0; i < k; i++) { if (vowels.includes(s[i])) count++; } let max = count; for (let i = k; i < s.length; i++) { if (vowels.includes(s[i])) count++; if (vowels.includes(s[i - k])) count--; max = Math.max(max, count); } return max; }

MarsgoatFri, May 5, 2023

Reference

回到題目列表