Problem
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".Example 2:
Given s = "leetcode", return "leotcede".Note:
The vowels does not include the letter "y".
Solution
Basic
public class Solution {
public static final Set<Character> vowelsSet;
static {
// initialize a list from an Character array
List<Character> vowelsList = Arrays.asList(
new Character[]{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'});
// use unmodifiableSet
vowelsSet = Collections.unmodifiableSet(new HashSet<>(vowelsList));
}
public String reverseVowels(String s) {
if (s == null) {
return null;
}
char[] chars = s.toCharArray();
int i = -1;
int j = s.length();
while (i < j) {
while (++i < j && !vowelsSet.contains(chars[i])) {}
while (i < --j && !vowelsSet.contains(chars[j])) {}
if (i >= j) {
break;
}
swap(chars, i, j);
}
return String.valueOf(chars);
}
public void swap(char[] chars, int i, int j) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}
}