LeetCode345-反转字符串中的元音字母

题目链接

英文链接:https://leetcode.com/problems/reverse-vowels-of-a-string/

中文链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string/

题目详述

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

示例 1:

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

示例 2:

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

说明:
元音字母不包含字母”y”。

题目详解

运用双指针从两侧往中间扫描即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class LeetCode_00345 {

public String reverseVowels(String s) {
char[] chars = s.toCharArray();
int i = 0;
int j = chars.length - 1;
while (i < j) {
while (i < j && !isVowel(chars[i])) {
++i;
}
while (i < j && !isVowel(chars[j])) {
--j;
}
swap(chars, i++, j--);
}
return new String(chars);
}

private boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
|| c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}

private void swap(char[] a, int i, int j) {
char t = a[i];
a[i] = a[j];
a[j] = t;
}
}