Problem Statement:
You are given a string, that contains only vowels and you need to get the longest substring that has all vowels “a’, ‘e’, ‘i’, ‘o’, ‘u’ in aplhabetical order.
Example
Input: word = “aeeeiiiioooauuuaeiou”
Output: 5
Solution
For this solution, we need to check for alphabets in increasing order of their vowels.
We take 2 variables,
“total” it will hold the value of the length of the substring.
“unique” is used to hold the count of number of vowels. As we need all 5 of them.
Then we iterate through the string and check if the next element is greater or equal to the previous element. If it is true then we increment the values.
else we reset both the values.
Solution in C++
#include <algorithm>
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
int longest_vowel_substring(string word)
{
const auto n = word.size();
int total = 1;
int unique = 1;
int ans = 0;
for (int i = 1; i != n; ++i)
{
if (word[i - 1] < word[i]) { // prev < current
total++;
unique++;
} else if (word[i] == word[i - 1]) { // prev == current
total++;
} else {
total = 1;
unique = 1;
}
if (unique == 5) {
ans = max(ans, total);
}
}
return ans;
}
int main()
{
string s1 = "aeeeiiiioooauuuaeiou";
cout<<"The longest vowel substring is "<< longest_vowel_substring(s1)<<endl;
return 0;
}
Output:
The longest vowel substring is 5