题目描述:
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello" Output: "holle"
Example 2:
Input: "leetcode" Output: "leotcede"
中文理解:给定一个字符串,反转韵母部分的字符串。
解题思路:设置两个指针start=0,end=s.length()-1,将字符串转为为char数组res,当res[start]和res[end]都为韵母时交换且start++,end--,若res[start]为声母,start++,若res[end]为声母,end--。
代码(java):
class Solution {
public String reverseVowels(String s) {
char []res=s.toCharArray();
int start=0,end=res.length-1;
while(start<end){
if(isVowels(res[start])&& isVowels(res[end])){
char tmp=res[start];
res[start]=res[end];
res[end]=tmp;
start++;
end--;
}
else if(!isVowels(res[start])){
start++;
}
else if(!isVowels(res[end])){
end--;
}
}
return new String(res);
}
public boolean isVowels(char ch){
ch= ch >= 'A' && ch <= 'Z' ? ch += 32 : ch;
return ch=='a' || ch=='o' || ch=='e' || ch=='i' || ch=='u';
}
}