ZhongKuo0228 / study

0 stars 0 forks source link

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

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

感覺有抓到 sliding window 的精髓

  1. 起始 cur_sum 為前 k 個元素的母音總數
  2. 每次滑動一個單位,更新 cur_sum 同時更新 ans
class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = list("aeiou")
        cur_sum = len([w for w in s[:k] if w in vowels])
        ans = cur_sum
        for i in range(k, len(s)):
            if s[i] in vowels:
                cur_sum += 1
            if s[i - k] in vowels:
                cur_sum -= 1
            ans = max(ans, cur_sum)
        return ans
fockspaces commented 1 year ago

GPT imrprove:

  1. 用 set 作為空間查找
  2. 不要用 list comprehension,直接用 for loop 來節省空間
  3. 命名改進
class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = set("aeiou")
        cur_vowel = max_vowels = 0
        for i in range(k):
            if s[i] in vowels:
                cur_vowel += 1
        max_vowels = cur_vowel
        for i in range(k, len(s)):
            if s[i] in vowels:
                cur_vowel += 1
            if s[i - k] in vowels:
                cur_vowel -= 1
            max_vowels = max(max_vowels, cur_vowel)
        return max_vowels