LeetCode/345. 反转字符串中的元音字母

345. 反转字符串中的元音字母

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例1 :

1
2
输入:"hello"
输出:"holle"

示例2:

1
2
输入:"leetcode"
输出:"leotcede"

提示:

  • 元音字母不包含字母 “y” 。

来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解:

本题基于双指针法,创建两个指针,一个指向头,一个指向尾,进行遍历即可。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public String reverseVowels(String s) {
char[] result = new char[s.length()];
Queue<Character> queue = new ArrayDeque<>(Arrays.asList('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'));
int left = 0, right = s.length() - 1;
while (left <= right) {
char temp1 = s.charAt(left);
char temp2 = s.charAt(right);
if (!queue.contains(temp1)) {
result[left++] = temp1;
} else if (!queue.contains(temp2)) {
result[right--] = temp2;
} else {
result[left++] = temp2;
result[right--] = temp1;
}
}
return new String(result);
}
}

Comments