试题:
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”
Note:
The vowels does not include the letter “y”.
代码:
import java.util.*;
class Solution {
public String reverseVowels(String s) {
HashSet<Character> vowels = new HashSet<>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
char[] out = new char[s.length()];
int left=0, right=s.length()-1;
while(left<=right){
char lchar = s.charAt(left);
char rchar = s.charAt(right);
if(!vowels.contains(lchar)){
out[left++] = lchar;
}
if(!vowels.contains(rchar)){
out[right--] = rchar;
}
if(vowels.contains(lchar) && vowels.contains(rchar)){
out[left++] = rchar;
out[right--] = lchar;
}
}
return String.valueOf(out);
}
}