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”.
解题思路
双指针,一个往前移动,一个往后移动,找到元音字母时则交换。
实现代码
// Runtime: 12 ms
public class Solution {
private static final String STR = "aeiouAEIOU";
private static final Set<Character> VOWELS = new HashSet<Character>(STR.length());
static {
for (int i = 0; i < STR.length(); i++) {
VOWELS.add(STR.charAt(i));
}
}
public String reverseVowels(String s) {
StringBuilder sb = new StringBuilder(s);
int left = 0;
int right = sb.length() - 1;
while (left < right) {
while (left < right && !isVowels(sb.charAt(left))) {
++left;
}
while (left < right && !isVowels(sb.charAt(right))) {
--right;
}
char temp = sb.charAt(left);
sb.setCharAt(left++, sb.charAt(right));
sb.setCharAt(right--, temp);
}
return sb.toString();
}
private boolean isVowels(char ch) {
return VOWELS.contains(ch);
}
}