给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串。
元音字母包括 'a'、'e'、'i'、'o'、'u',且可能以大小写两种形式出现。
示例 1:
输入:s = "hello"
输出:"holle"
示例 2:
输入:s = "leetcode"
输出:"leotcede"
提示:
1 <= s.length <= 3 * 105
s 由 可打印的 ASCII 字符组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string
思路:使用双重指针start/end,分别指向字符串的头部和尾部;在start<end的时候进行反转,start与end所指字母均为元音字母的时候进行替换,否则不替换,指针移动。
注意:由于使用String,charAt(index)进行取值,所以需要注意越界问题。
class Solution {
public String reverseVowels(String s) {
//因为String无法修改,所以利用StringBuffer来进行改变
StringBuffer result = new StringBuffer(s);
int start = 0;
int end = s.length()-1;
char temp;
while(start<end){
while (!isVo(s.charAt(start))&&start<=s.length()-2){
start++;
}
while (!isVo(s.charAt(end))&&end>=1){
end--;
}
if (start<end){
temp = s.charAt(start);
result.setCharAt(start,s.charAt(end));
result.setCharAt(end,temp);
}
start++;
end--;
}
return result.toString();
}
/**
* 判断是否为元音字母
* @param ch
* @return true:是元音字母 false:不是元音字母
*/
public boolean isVo(char ch){
String s = "aeiouAEIOU";
if (s.indexOf(ch)>=0){
return true;
}
return false;
}
}