反转字符串中的元音字母

问题陈述

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

1
2
3
4
输入:"hello"
输出:"holle"
https://github.com/Zhi-Tu/My-Album/blob/master/photos/leetcode.png
https://github.com/Zhi-Tu/My-Album/blob/master/photos/const.png

思路分析

可将元音字母存入一个HashSet,双指针首尾遍历字符串,遇到元音字母则交换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private final static HashSet<Character> vowels = new HashSet<>(
Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
//Arrays.asList(num)将num数组转换为list。
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);
}