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”.
将字符串里的元音字符交换位置.
public class Solution {
public String reverseVowels(String s) {
char[] str = s.toCharArray();
Set<Character> set = new HashSet<>();
set.add('a');
set.add('o');
set.add('e');
set.add('i');
set.add('u');
set.add('A');
set.add('O');
set.add('E');
set.add('I');
set.add('U');
int start = 0;
int end = str.length - 1;
while (true) {
while (start < end && !set.contains(str[start])) start++;
while (start < end && !set.contains(str[end])) end--;
if (start >= end) {
return new String(str);
} else {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
}
}