Skip to content

Commit 9cb7e54

Browse files
committed
Merge branch 'master' of github.com:BaffinLee/leetcode-javascript
2 parents df23c5e + 500b87f commit 9cb7e54

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# 1456. Maximum Number of Vowels in a Substring of Given Length
2+
3+
- Difficulty: Medium.
4+
- Related Topics: String, Sliding Window.
5+
- Similar Questions: Maximum White Tiles Covered by a Carpet, Minimum Recolors to Get K Consecutive Black Blocks, Length of the Longest Alphabetical Continuous Substring.
6+
7+
## Problem
8+
9+
Given a string `s` and an integer `k`, return **the maximum number of vowel letters in any substring of **`s`** with length **`k`.
10+
11+
**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.
12+
13+
 
14+
Example 1:
15+
16+
```
17+
Input: s = "abciiidef", k = 3
18+
Output: 3
19+
Explanation: The substring "iii" contains 3 vowel letters.
20+
```
21+
22+
Example 2:
23+
24+
```
25+
Input: s = "aeiou", k = 2
26+
Output: 2
27+
Explanation: Any substring of length 2 contains 2 vowels.
28+
```
29+
30+
Example 3:
31+
32+
```
33+
Input: s = "leetcode", k = 3
34+
Output: 2
35+
Explanation: "lee", "eet" and "ode" contain 2 vowels.
36+
```
37+
38+
 
39+
**Constraints:**
40+
41+
42+
43+
- `1 <= s.length <= 105`
44+
45+
- `s` consists of lowercase English letters.
46+
47+
- `1 <= k <= s.length`
48+
49+
50+
51+
## Solution
52+
53+
```javascript
54+
/**
55+
* @param {string} s
56+
* @param {number} k
57+
* @return {number}
58+
*/
59+
var maxVowels = function(s, k) {
60+
var i = 0;
61+
var j = 0;
62+
var count = isVowel(s, j) ? 1 : 0;
63+
var max = count;
64+
while (j < s.length - 1) {
65+
j++;
66+
count += (isVowel(s, j) ? 1 : 0);
67+
if (j - i > k - 1) {
68+
count -= (isVowel(s, i) ? 1 : 0);
69+
i++;
70+
}
71+
max = Math.max(max, count);
72+
}
73+
return max;
74+
};
75+
76+
var isVowel = function(s, i) {
77+
return ['a', 'e', 'i', 'o', 'u'].includes(s[i]);
78+
};
79+
```
80+
81+
**Explain:**
82+
83+
nope.
84+
85+
**Complexity:**
86+
87+
* Time complexity : O(n).
88+
* Space complexity : O(1).

0 commit comments

Comments
 (0)