【题目】
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
【题意】
将字符串中所有的元音字母逆转,辅音字母的位置不变,其中元音字母有五个a,e,i,o,u,需要注意的是大写的也算,所以总共有十个字母。我们写一个isVowel的函数来判断当前字符是否为元音字母,如果两边都是元音字母,那么我们交换,如果左边的不是,向右移动一位,如果右边的不是,则向左移动一位
【分析】
1)定义两个指标i,j,分别指向字符串最前端和字符串最尾端;
2)遍历字符串,判断字符串中对应位置字符是否为元音字符,如果是元音字符,停止遍历,然后在另一方向找到对应位置的元音字符位置,找到后,将两个位置字符进行交换,然后继续遍历,直到遍历结束。
3)遍历方式类似于快速排序中的遍历调整位置。
【实现】
public class Solution {
public boolean isVowels(char c){
// 将字符c同一转换为小写字符
c = Character.toLowerCase(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
return true;
return false;
}
public String reverseVowels(String s) {
int i = 0;
int j = s.length() - 1;
char[] ss = s.toCharArray();
char temp;
while (i < j){
while (i < j && (!isVowels(ss[i]))){
i++;
}
while (i < j && (!isVowels(ss[j]))){
j--;
}
// 交换两个ss[i]与ss[j]
temp = ss[i];
ss[i] = ss[j];
ss[j] = temp;
i++;
j--;
}
return new String(ss);
}
}