Reverse Vowels of a String
Hii Viewers, Welcome to my DSA blog let’s dive through the problem of Reversing Vowels of a String.
Problem statement
Given a string s
, reverse only all the vowels in the string and return it.
The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both lower and upper cases, more than once.
Example 1:
Input: s = "IceCreAm"
Output: "AceCreIm"
Explanation:
The vowels in s
are ['I', 'e', 'e', 'A']
. On reversing the vowels, s becomes "AceCreIm"
.
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Constraints:
1 <= s.length <= 3 * 10<sup>5</sup>
s
consist of printable ASCII characters.
Intuition
Our primary task would be to find out if the string contains the vowels or not, so we write a method to check for vowels in the string. If you think deeply, you can identify a pattern in this problem that is two pointers. We can use two pointers logic to traverse the string in both left and right directions in the process if we don’t find any Vowels then we will just continue i.e increment the left pointer and decrement the right pointer. If we encounter any Vowel’s in the process, we will do a swap of the chars[left] and chars[right] and this continues until the base condition while(left<right) is false.
Program
class Solution {
public boolean isVowel(char c)
{
c = Character.toLowerCase(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
public String reverseVowels(String s) {
//forward
int left=0;
int right=s.length()-1;
char[] chars = s.toCharArray();
while(left<right)
{
while(left<right && !isVowel(chars[left]))
{
left++;
}
while(left<right && !isVowel(chars[right]))
{
right--;
}
char temp=chars[left];
chars[left]=chars[right];
chars[right]=temp;
left++;
right--;
}
return new String(chars);
}
}
Thanks for viewing this article your feedback helps me to improve and write more articles in future.
Subscribe to my newsletter
Read articles from yuvan bajjurla directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by