Contents

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

1456.MaxVowelsSubstr.py

class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = set('aeiou')  # 定義母音集合
        count = sum(1 for char in s[:k] if char in vowels)  # 使用列表生成式來計算母音數量

        # 初始化最大母音數量為目前的count
        max_count = count

        # 滑動窗口
        for i in range(k, len(s)):
            # 如果左邊的字母是母音,則減少count
            if s[i - k] in vowels:
                count -= 1
            # 如果右邊的字母是母音,則增加count
            if s[i] in vowels:
                count += 1
            # 更新最大母音數量
            max_count = max(max_count, count)

        return max_count


if __name__ == '__main__':
    sol = Solution()
    assert sol.maxVowels(s="abciiidef", k=3) == 3
    assert sol.maxVowels(s="aeiou", k=2) == 2
    assert sol.maxVowels(s="leetcode", k=3) == 2

lc1456MaxVowelsSubstr_test.go

package lc

import "testing"

func maxVowels(s string, k int) int {
	vowels := map[rune]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true}
	count := 0

	// 使用for迴圈來計算第一個長度為k的子字串中的母音字母數量
	for _, char := range s[:k] {
		if _, exists := vowels[char]; exists {
			count++
		}
	}

	maxCount := count

	// 滑動窗口
	for i := k; i < len(s); i++ {
		// 如果左邊的字母是母音,則減少count
		if _, exists := vowels[rune(s[i-k])]; exists {
			count--
		}
		// 如果右邊的字母是母音,則增加count
		if _, exists := vowels[rune(s[i])]; exists {
			count++
		}
		// 更新最大母音數量
		if count > maxCount {
			maxCount = count
		}
	}

	return maxCount
}

func TestMaxVowels(t *testing.T) {
	tests := []struct {
		s      string
		k      int
		result int
	}{
		{"abciiidef", 3, 3},
		{"aeiou", 2, 2},
		{"leetcode", 3, 2},
	}

	for _, test := range tests {
		got := maxVowels(test.s, test.k)
		if got != test.result {
			t.Errorf("For s=%s, k=%d; expected %d but got %d", test.s, test.k, test.result, got)
		}
	}
}