Leetcode-1456

Maximum Number of Vowels in a Substring of Given Length

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

Difficulty: Medium

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cstring>

class Solution {
public:
    int maxVowels(std::string s, int k) {
        int n = s.size(), m = std::min(n, k);
        int num = 0;
        for (int i = 0; i < m; ++i) {
            if (isVowel(s[i])) {
                ++num;
            }
        }
        int max_num = num;
        for (int i = m; i < n; ++i) {
            if (isVowel(s[i])) {
                ++num;
            }
            if (isVowel(s[i - k])) {
                --num;
            }
            max_num = std::max(num, max_num);
        }
        return max_num;
    }

private:
    bool isVowel(char c) {
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            return true;
        }        return false;
    }
};

Leetcode-1456