[閒聊] 每日leetcode 75 - Day7 - 6

作者: yam276 ('_')   2025-06-09 17:11:39
1456. Maximum Number of Vowels in a Substring of Given Length
題目:
維護一個 sliding window
看 k 大小的窗口滑到底
窗口內最多有幾個母音
思路:
每次滑動看進來的是不是母音
離開的是不是母音
多一個 if i>= k 判斷就可以省一個起始窗口 for
Code:
impl Solution {
pub fn max_vowels(s: String, k: i32) -> i32 {
pub fn is_vowel(c: char) -> bool {
matches!(c, 'a' | 'e' | 'i' | 'o' | 'u')
}
let s_chars: Vec<char> = s.chars().collect();
let k = k as usize;
let mut count = 0;
let mut max_count = count;
for (i, c) in s_chars.iter().enumerate() {
if is_vowel(*c) {
count += 1;
}
if i >= k {
if is_vowel(s_chars[i - k]) {
count -= 1;
}
}
max_count = max_count.max(count);
}
max_count
}
}

Links booklink

Contact Us: admin [ a t ] ucptt.com