Question:
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"
Solution:
我们只能交换元音字母。此题和将奇数放后面偶数放前面类似。
JAVAclass Solution {
public String reverseVowels(String s) {
char[] a = s.toCharArray();
int i=0;int j=a.length-1;
while(i < j) {
while(i < j && !isVowel(a[i])) {
i++;
}
while(j >= 0 && !isVowel(a[j])) {
j--;
}
if (i < j) {
char t = a[i];
a[i] = a[j];
a[j] = t;
i++;j--;
}
}
return new String(a);
}
private boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}
}
已有0条评论
还没有任何评论,你来说两句吧!