反轉字符串的元音字母>>>
雙指針
:定義兩個指針,從數組兩端向數組中間遍歷,若發現元音字母則進行交換,否則進行遍歷。
class Solution {
public String reverseVowels(String s) {
String tool="aoeiuAOEIU";
char[] rs = s.toCharArray();
int left = 0;
int right = s.length()-1;
while (left<right){
//左右兩個都爲原因字母則交換
if(isVowel(rs[left])&&isVowel(rs[right])){
char temp =rs[left];
rs[left]=rs[right];
rs[right]=temp;
left++;
right--;
}else if(!isVowel(rs[left])){//否則
left++;
}else if(!isVowel(rs[right])){
right--;
}
}
return new String(rs);
}
// 判斷是不是元音,如果不是元音才返回 true
private boolean isVowel(char ch) {
// 這裏要直接用 return 語句返回,不要返回 true 或者 false
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'
||ch=='A'|| ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
}