LeetCode //C - 1456. Maximum Number of Vowels in a Substring of Given Length
2023-12-24 22:31:15
1456. Maximum Number of Vowels in a Substring of Given Length
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.
Constraints:
- 1 < = s . l e n g t h < = 1 0 5 1 <= s.length <= 10^5 1<=s.length<=105
- s consists of lowercase English letters.
- 1 <= k <= s.length
From: LeetCode
Link: 1456. Maximum Number of Vowels in a Substring of Given Length
Solution:
Ideas:
- s is the input string.
- k is the length of the substring.
- isVowel is a helper function to check if a character is a vowel.
- The function first counts the number of vowels in the first window of size k.
- Then it iterates through the string, sliding the window one character at a time, updating the vowel count, and keeping track of the maximum vowel count found.
Code:
// Helper function to check if a character is a vowel
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
int maxVowels(char *s, int k) {
int maxVowelCount = 0, currentVowelCount = 0;
// Initial count of vowels in the first window
for (int i = 0; i < k; ++i) {
if (isVowel(s[i])) {
currentVowelCount++;
}
}
maxVowelCount = currentVowelCount;
// Slide the window and update counts
for (int i = k; s[i] != '\0'; ++i) {
if (isVowel(s[i])) {
currentVowelCount++;
}
if (isVowel(s[i - k])) {
currentVowelCount--;
}
if (currentVowelCount > maxVowelCount) {
maxVowelCount = currentVowelCount;
}
}
return maxVowelCount;
}
文章来源:https://blog.csdn.net/navicheung/article/details/135187462
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!