Featured image of post LeetCode 75 - 1456. Maximum Number of Vowels in a Substring of Given Length

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

Description

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:

1
2
3
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.

Example 2:

1
2
3
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.

Example 3:

1
2
3
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.
  • 1 <= k <= s.length

Solutions

Approach: Use a sliding window, traverse sequentially, and then obtain the maximum value.

Solution 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    int maxVowels(string s, int k) {
        // 创建映射表,便于以logn的复杂度查找
        std::set<char> vowel{'a', 'e', 'i', 'o', 'u'};
        int begin{};
        int end = k;
        int max{};

        while (end <= s.size()) {
            int num{};
            for (int i = begin; i < end; ++i) {
                if (auto it = vowel.find(s[i]); it != vowel.end()) {
                    num++;
                }
            }
            begin++;
            end++;
            if (num > max)
                max = num;
        }
        return max;
    }
};

The issue with this solution is that the time complexity is too high, leading to a timeout.

Solution 2:

A function is encapsulated here to conveniently determine whether a character is a vowel. At the same time, the vowel map is set as an inline static member variable to improve performance.

 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
class Solution {
    inline static std::set<char> vowel{'a', 'e', 'i', 'o', 'u'};
    bool isVowel(char c) {
        if (auto it = vowel.find(c); it != vowel.end()) {
            return true;
        }
        return false;
    }

public:
    int maxVowels(string s, int k) {
        int max{};
        for (int i = 0; i < k; i++) {
            if (isVowel(s[i])) {
                max++;
            }
        }
        int num = max;
        for (int i = k; i < s.size(); ++i) {
            if (isVowel(s[i - k])) {
                num--;
            }
            if (isVowel(s[i])) {
                num++;
            }

            // 比较交换最大数值
            max = std::max(num, max);
        }
        return max;
    }
};