Problem Statement Source
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 = “hello”
Output: “holle”
Example 2:
Input: s = “leetcode”
Output: “leotcede”
Constraints:
1 <= s.length <= 3 * 10^5
s
 consist of printable ASCII  characters.
Read the question first.
Two Pointers [Try to think in this direction]
Solution:
class Solution {
public String reverseVowels (String s ) {
char [] charArr = s. toCharArray ();
String vowels = "aeiouAEIOU" ;
int i = 0 ;
int j = s. length () - 1 ; // Start from the end of the string
while (i < j) {
while (i < j && ! vowels. contains (String. valueOf (charArr[i]))) {
i ++ ;
}
while (i < j && ! vowels. contains (String. valueOf (charArr[j]))) {
j -- ;
}
// Swap the vowels at positions i and j
if (i < j) {
char temp = charArr[i];
charArr[i] = charArr[j];
charArr[j] = temp;
i ++ ;
j -- ;
}
}
return new String (charArr);
}
}