题目描述
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入:“hello”
输出:“holle”
示例 2:
输入:“leetcode”
输出:“leotcede”
提示:
元音字母不包含字母 “y”
代码
class Solution {
public String reverseVowels(String s) {
if(s == null || s.length() == 0) return s;
String vowels = "aeiouAEIOU";
char[] chars = s.toCharArray();
int start = 0;
int end = s.length() - 1;
while(start < end){
while(start < end && !vowels.contains(chars[start]+ "")){
start++;
}
while(start < end && !vowels.contains(chars[end]+"")){
end--;
}
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
return new String(chars);
}
}
class Solution {
private final static HashSet<Character> vowels = new HashSet<>(
Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
public String reverseVowels(String s) {
if(s == null) return null;
int i =0, j = s.length() - 1;
char[] result = new char[s.length()];
while(i <= j){
char ci = s.charAt(i);
char cj = s.charAt(j);
if(!vowels.contains(ci)){
result[i++] = ci;
}else if(!vowels.contains(cj)){
result[j--] = cj;
}else{
result[i++] = cj;
result[j--] = ci;
}
}
return new String(result);
}
}
参考:https://leetcode.com/problems/reverse-vowels-of-a-string/discuss/81225/Java-Standard-Two-Pointer-Solution