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
public class Solution {
public String reverseVowels(String s) {
if(s == null) return null;
int left = 0;
int right = s.length() - 1;
char[] tmp = s.toCharArray();
while(left < right) {
while( !isVowel(tmp[left]) && left < right) left++;
while( !isVowel(tmp[right]) && left < right) right--;
if(left >= right) break;
// swap and continue;
char t = tmp[left];
tmp[left] = tmp[right];
tmp[right] = t;
left++;
right--;
}
return new String(tmp);
}
public boolean isVowel(char a) {
return a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' ||
a == 'A' || a == 'E' || a == 'I' || a == 'O' || a == 'U';
}
}