Leetcode 345. Reverse Vowels of a String
Given a string s
, reverse only the vowels of the string and return it.
The vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’, and they can appear in both lower and upper cases (like ‘A’, ‘E’, ‘I’, ‘O’, ‘U’).
import java.util.HashSet;
import java.util.Set;
public class ReverseVowels {
public static String reverseVowels(String s) {
if (s == null || s.isEmpty()) {
return s;
}
Set<Character> vowels = new HashSet<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
vowels.add('A');
vowels.add('E');
vowels.add('I');
vowels.add('O');
vowels.add('U');
char[] chars = s.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
while (left < right && !vowels.contains(chars[left])) {
left++;
}
while (left < right && !vowels.contains(chars[right])) {
right--;
}
if (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
return new String(chars);
}
public static void main(String[] args) {
String input = "hello";
String result = reverseVowels(input);
System.out.println(result); // Output: "holle"
input = "leetcode";
result = reverseVowels(input);
System.out.println(result); // Output: "leotcede"
}
}
n
is the length of the string. Each character is processed at most twice (once by each pointer).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?