345. Reverse Vowels of a String
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”.
Note:
The vowels does not include the letter “y”.
class Solution {
public String reverseVowels(String s) {
char[] chars=s.toCharArray();
String point="aeiouAEIOU";
int l=s.length()-1;
int i=0;
char temp;
for(;i<l;i++){
if(point.contains(chars[i]+"")){//扫描到前面的元音字母
System.out.println(chars[i]);
for(;l>i;l--){
if(point.contains(chars[l]+"")){//扫描到后面的,交换
System.out.println(chars[l]);
temp=chars[i];
chars[i]=chars[l];
chars[l]=temp;
l--;
break;//交换结束,退出l遍历循环
}
}
}
}
return new String(chars);
}
}
improve
public String reverseVowels(String s) {
char[] chars=s.toCharArray();
String point="aeiouAEIOU";
int l=s.length()-1;
int i=0;
char temp;
while(i<l){
while(i<l&&!point.contains(chars[i]+"")){
i++;
}
while(l>i&&!point.contains(chars[l]+"")){
l--;
}
temp=chars[i];
chars[i]=chars[l];
chars[l]=temp;
i++;
l--;
}
return new String(chars);
}