Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1456. 定长子串中元音的最大数目 #39

Open
zpc7 opened this issue Aug 26, 2022 · 0 comments
Open

1456. 定长子串中元音的最大数目 #39

zpc7 opened this issue Aug 26, 2022 · 0 comments
Labels
中等 LeetCode 难度定级 滑动窗口

Comments

@zpc7
Copy link
Owner

zpc7 commented Aug 26, 2022

1456. 定长子串中元音的最大数目

/**
 * @param {string} s
 * @param {number} k
 * @return {number}
 */
var maxVowels = function (s, k) {
    const vowel = new Set(['a', 'e', 'i', 'o', 'u']); // 元音
    let count = 0;  // 滑动窗口中元音的个数
    let max = 0; // 窗口中, 是元音的最多个数

    // 窗口的右边界从0开始!
    for (let i = 0; i < s.length; i++) {
        // i=k的时候, s[0] 滑出窗口了
        if (i >= k) {
            // 判断滑出去的这个元素是不是元音
            // 如果是的话, 那么count - 1
            if (vowel.has(s[i - k])) {
                count -= 1;
            }
        }
        // i 所处的位置是窗口的最右侧, 判断新进入窗口的值是不是元音
        if (vowel.has(s[i])) {
            count += 1;
        }
        // 存储相对大的值
        // 并且如果最大值等于K, 说明窗口中每一个都是元音, 就不再滑动窗口了
        if (count > max) {
            max = count;
            if (max === k) return k;
        }
    }
    return max;
};
@zpc7 zpc7 added 中等 LeetCode 难度定级 滑动窗口 labels Aug 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 LeetCode 难度定级 滑动窗口
Projects
None yet
Development

No branches or pull requests

1 participant