题目内容
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”.
题目分析
翻转字符串中的元音,如样例所示。在样例2中,leetcode中的元音为,eeoe,翻转后的元音序列为eoee。
方法是通过建立两个指针,一个从左向右走,一个从右向左走。左起的第一个元音与右起的第一个元音交换位置,如果两个元音位置重合则,结束。
代码一,直接做
public class Solution {
public String reverseVowels(String s) {
if (s == null) {
throw new IllegalArgumentException();
}
if (s.length() <= 1) {
return s;
}
char[] str = s.toCharArray();
for (int i = 0, j = str.length - 1; i < j; i++, j--) {
while (i < j && !isVowel(str[i])) i++;
while (i < j && !isVowel(str[j])) j--;
if (i <= j) swap(str, i, j);
}
return new String(str);
}
private boolean isVowel(char ch) {
char c = Character.toLowerCase(ch);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
private void swap(char[] str, int i, int j) {
char tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
}
代码二,利用stringBuilder来做,速度比代码一慢了一倍多,因为两个指针不是交汇就停止了,而是要走到头。
public class Solution {
public String reverseVowels(String s) {
StringBuilder sb = new StringBuilder();
int j = s.length() - 1;
for (int i = 0; i < s.length(); i++)
{
if ("AEIOUaeiou".indexOf(s.charAt(i)) != -1)
{
while (j >= 0 && "AEIOUaeiou".indexOf(s.charAt(j)) == -1)
{
j--;
}
sb.append(s.charAt(j));
j--;
}
else
sb.append(s.charAt(i));
}
return sb.toString();
}
}