- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Number of Vowels in a Substring of Given Length in C++
Suppose we have a string s and an integer k. We have to find the maximum number of vowel letters in any substring of s with length k.
So, if the input is like s = "abciiidef", k = 3, then the output will be 3
To solve this, we will follow these steps −
cnt := 0
Define one set m
for each vowel v, do
insert v into m
ret := 0
for initialize i := 0, when i < k, update (increase i by 1), do −
cnt := cnt + (1 when s[i] is in m, otherwise 0)
ret := maximum of ret and cnt
n := size of s
for initialize i := k, when i < n, update (increase i by 1), do −
if s[i - k] is member of m, then −
(decrease cnt by 1)
cnt := cnt + (1 when s[i] is in m, otherwise 0)
ret := maximum of ret and cnt
return ret
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxVowels(string s, int k) { int cnt = 0; set<char> m; for (auto it : { 'a', 'e', 'i', 'o', 'u' }) m.insert(it); int ret = 0; for (int i = 0; i < k; i++) { cnt += m.count(s[i]) ? 1 : 0; } ret = max(ret, cnt); int n = s.size(); for (int i = k; i < n; i++) { if (m.count(s[i - k])) { cnt--; } cnt += m.count(s[i]) ? 1 : 0; ret = max(ret, cnt); } return ret; } }; main(){ Solution ob; cout << (ob.maxVowels("abciiidef",3)); }
Input
"abciiidef",3
Output
3
To Continue Learning Please Login
Login with Google