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”
在字符串中,把其中的元音字母逆序。
元音是指"a, e, i, o, u",还有大写的
双指针。
左右指针指向元音字母时,调换位置,
否则指针向前进(后退)
注意还有大写的元音字母
class Solution {
public String reverseVowels(String s) {
char[] arr = s.toCharArray();
int n = arr.length;
int left = 0;
int right = n - 1;
while(left < right) {
if(isVowel(arr[left]) && isVowel(arr[right])) {
swap(arr, left, right);
left ++;
right --;
} else {
if(!isVowel(arr[left])) left ++;
else right --;
}
}
return new String(arr);
}
boolean isVowel(char chr) {
char ch = Character.toLowerCase(chr);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true;
return false;
}
void swap(char[] arr, int left, int right) {
char tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
}
}