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".
主要就是搞清楚元音字母是" a e i o u “这五个就好了,当然还包括它们的大写。
public String reverseVowels(String s) {
StringBuilder sb=new StringBuilder(s);
int frontPointer=0;
int behindPointer=s.length()-1;
while(frontPointer<behindPointer){
while(frontPointer<s.length()&&!isVowels(sb.charAt(frontPointer))){
frontPointer++;
}
while(behindPointer>=0&&!isVowels(sb.charAt(behindPointer))){
behindPointer--;
}
if(frontPointer<behindPointer){
char tmp=sb.charAt(frontPointer);
sb.setCharAt(frontPointer, sb.charAt(behindPointer));
sb.setCharAt(behindPointer, tmp);
frontPointer++;
behindPointer--;
}
}
return sb.toString();
}
public boolean isVowels(char c){
return c=='a'||c=='A'||c=='e'||c=='E'||c=='i'||c=='I'
||c=='o'||c=='O'||c=='u'||c=='U';
}
大神判断是否是元音字母是用 hashset 做的,也蛮好的。
public class Solution {
public String reverseVowels(String s) {
char[] list=s.toCharArray();
Set<Character> vowels = new HashSet<>(Arrays.asList(new Character[]{'a','e','i','o','u','A','E','I','O','U'}));
for (int i=0, j=list.length-1; i<j; ) {
if (!set.contains(list[i])) {
i++;
continue;
}
if (!set.contains(list[j])) {
j--;
continue;
}
char temp=list[i];
list[i]=list[j];
list[j]=temp;
i++;
j--;
}
return String.valueOf(list);
}
}