05 August 2008
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
1
2
Input: "hello"
Output: "holle"
Example 2:
1
2
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter “y”.
只翻转一个字符串中的元音字符,题目中没说只是小写,所以大写的字符也算,可以直接双指针left和right,如果都指向元音字符,交换;如果left不是,右移一位left;如果right不是,左移一位right;当left大于等于right的时候停止。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public String reverseVowels(String s) {
if (s == null || s.length() == 0 || s.length() == 1) {
return s;
}
char[] word = s.toCharArray();
int left = 0, right = s.length() - 1;
while(left <= right){
if(isVowels(word[left]) && isVowels(word[right])){
swap(word, left, right);
left++;
right--;
}else if (!isVowels(word[left])){
left++;
}else {
right--;
}
}
return new String(word);
}
public boolean isVowels(char c){
return c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U';
}
public void swap(char[] ch,int left,int right){
char temp = ch[left];
ch[left] = ch[right];
ch[right] = temp;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public String reverseVowels(String s) {
if(s == null || s.length()==0 || s.length() == 1) return s;
String vowels = "aeiouAEIOU";
char[] chars = s.toCharArray();
int left = 0;
int right = s.length()-1;
while(left < right){
while(left < right && !vowels.contains(chars[left]+"")) {//转换成字符串检查是否存在
left++;
}
while(left < right && !vowels.contains(chars[right]+"")) {
right--;
}
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
}