Given a string s, reverse only all the vowels in the string and return it.
Input: "hello" → Output: "holle"Input: "leetcode" → Output: "leotcede"
Two pointers. Move left pointer right until it hits a vowel. Move right pointer left until it hits a vowel. Swap and continue.
- Set vowels = {a,e,i,o,u,A,E,I,O,U}.
- lo=0, hi=n-1.
- While lo
- Swap chars[lo] and chars[hi], lo++, hi--.
import java.util.*;
class Solution {
public String reverseVowels(String s) {
Set<Character> vowels = new HashSet<>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
char[] c = s.toCharArray();
int lo = 0, hi = c.length - 1;
while (lo < hi) {
while (lo < hi && !vowels.contains(c[lo])) lo++;
while (lo < hi && !vowels.contains(c[hi])) hi--;
if (lo < hi) { char t = c[lo]; c[lo] = c[hi]; c[hi] = t; lo++; hi--; }
}
return new String(c);
}
}
- Time Complexity: O(N)
- Space Complexity: O(1) extra