tutorialcup
Reverse Vowels of a String Leetcode Solution
Problem Statement
In this problem a string is given and we have to reverse only the vowels of this string.
Example
"hello"
"holle"
Explanation:
before reversing : "hello"
after reversing : "holle"
"leetcode"
"leotcede"
Explanation:
Approach 1 (Using Stack)
We just have to reverse the vowels present in input string. So we can store all the vowels in a stack in the same order from left to right. Then again we can traverse the string and for each vowel character from left to right we will replace it with the topmost value of the stack.
Algorithm
- Store all the vowel characters in a set.
- Create a stack and push all vowel characters present in the input string from left to right.
- Now again traverse the string for each character. If current character is vowel, replace it with the topmost character of the stack (rightmost vowel character of input string) and remove it from the stack.
- Return the converted string.
Implementation for Reverse Vowels of a String Leetcode Solution
C++ Program
#include
using namespace std;
string reverseVowels(string s) {
set vowels={'a','e','i','o','u','A','E','I','O','U'};
stack stack;
for(char c:s)
{
if(vowels.count(c)) stack.push(c);
}
for(char& c:s)
{
if(vowels.count(c))
{
c=stack.top();
stack.pop();
}
}
return s;
}
int main()
{
string s="leetcode";
cout
www.tutorialcup.com/leetcode-solutions/reverse-vowels-of-...
Reverse Vowels of a String Leetcode Solution
Problem Statement
In this problem a string is given and we have to reverse only the vowels of this string.
Example
"hello"
"holle"
Explanation:
before reversing : "hello"
after reversing : "holle"
"leetcode"
"leotcede"
Explanation:
Approach 1 (Using Stack)
We just have to reverse the vowels present in input string. So we can store all the vowels in a stack in the same order from left to right. Then again we can traverse the string and for each vowel character from left to right we will replace it with the topmost value of the stack.
Algorithm
- Store all the vowel characters in a set.
- Create a stack and push all vowel characters present in the input string from left to right.
- Now again traverse the string for each character. If current character is vowel, replace it with the topmost character of the stack (rightmost vowel character of input string) and remove it from the stack.
- Return the converted string.
Implementation for Reverse Vowels of a String Leetcode Solution
C++ Program
#include
using namespace std;
string reverseVowels(string s) {
set vowels={'a','e','i','o','u','A','E','I','O','U'};
stack stack;
for(char c:s)
{
if(vowels.count(c)) stack.push(c);
}
for(char& c:s)
{
if(vowels.count(c))
{
c=stack.top();
stack.pop();
}
}
return s;
}
int main()
{
string s="leetcode";
cout
www.tutorialcup.com/leetcode-solutions/reverse-vowels-of-...