文章目錄
-
-
- 題目描述
- 思路及解答
-
題目描述
編寫一個函數,以字元串作為輸入,反轉該字元串中的元音字母。
示例 1:
輸入: “hello”
輸出: “holle”
示例 2:
輸入: “leetcode”
輸出: “leotcede”
說明:
元音字母不包含字母"y"。
思路及解答
/*
思路:
使用雙指針法
如果遇到前面的指針和後面的指針都遇到元音則交換
*/
class Solution {
public String reverseVowels(String s) {
int len = s.length();
if(s == null){
return null;
}
//如果作指針和右指針同時遇到元音字母,則交換;如果沒有遇到則移動左右指針,因為涉及到字母的交換以及字元的不可變性,是以這裡使用字元串數組
//将字元串轉化為字元串數組
char[] chars = s.toCharArray();
//定義左右指針
int left = 0;
int right = len-1;
while(left < right){
while(!isVowel(chars[left]) && (left<right))
left++;
while(!isVowel(chars[right]) && (left<right))
right--;
if(isVowel(chars[left]) && isVowel(chars[right])){
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
//将字元串數組轉化為字元串
String ss = new String(chars);
return ss;
}
//驗證這個字元是否為元音字元
public boolean isVowel(char c){
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
return true;
}
if(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'){
return true;
}
return false;
}
}