编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: “hello”
输出: “holle”
示例 2:
输入: “leetcode”
输出: “leotcede”
说明:
元音字母不包含字母"y"。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public String reverseVowels(String s) {
char[] ss = s.toCharArray();
int low = 0;
int high = ss.length-1;
while(low<high){
if(!isValid(ss[low])){
low++;
continue;
}
if(!isValid(ss[high])){
high--;
continue;
}
swap(ss,low,high);
low++;
high--;
}
String res = "";
for(char ch : ss){
res = res+ch;
}
return res;
}
public boolean isValid(char ch){
if(ch=='a' || ch=='A' || ch=='e' || ch=='E' || ch=='i' ||
ch=='I' || ch=='o' || ch=='O' || ch=='u' || ch=='U'){
return true;
}
return false;
}
public void swap(char[] s, int i, int j){
char temp = s[j];
s[j] = s[i];
s[i] = temp;
}
}