345. Reverse Vowels of a String

LeetCode 345. Reverse Vowels of a String

如题所述,将字符串中的原因字母逆序排列。双指针问题。代码和快排中一次partition的操作相似。

代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public String reverseVowels(String s) {
if (s == null || s.length() == 0) {
return "";
}
char[] chars = s.toCharArray();
HashSet<Character> hs = new HashSet<>();
String vowel = "aeiouAEIOU";
int i = 0, j = s.length() - 1, n = s.length();
while (i < j) {
while (i < j && vowel.indexOf(chars[i]) < 0) {
i++;
}
while (i < j && vowel.indexOf(chars[j]) < 0) {
j--;
}
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
i++;
j--;
}
return new String(chars);
}

题目不难,要点有两个。

  • 判断一个字母是不是元音字母,显然想建立一个HashSet,将所有元音字母塞进去,判断一个新字母在不在这个HashSet里。但是考虑到字母数量较少,用一个字符串判断更加简洁。

  • 双指针的双层三while。外层判断越界,内层判断元素性质前也要检查越界。