反转字符串中的元音字母

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

示例 1:

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

示例 2:

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

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

代码

首先得注意一下字母的大小写

双指针

这种方法先创建一个元音字符的数组再进行for循环遍历判断

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
30
31
32
33
34
private static char[] chars = new char[]{'a', 'A',
'e', 'E',
'i', 'I',
'o', 'O',
'u', 'U'};

public String reverseVowels(String s) {
if (s == null) return null;
if (s.length() < 2) return s;
char[] chars = s.toCharArray();
int pre = 0;
int suf = s.length() - 1;
while (pre < suf) {
if (!isVowel(chars[pre])) {
pre++;
} else if (!isVowel(chars[suf])) {
suf--;
} else {
char temp = chars[pre];
chars[pre] = chars[suf];
chars[suf] = temp;
pre++;
suf--;
}
}
return new String(chars);
}

private static boolean isVowel(char c) {
for (char cc : chars) {
if (cc == c) return true;
}
return false;
}

与上面的方法相比,主要是将创建的元音字符数组去掉,使用switch判断字符,执行效率比数组要高

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public String reverseVowels(String s) {
if (s == null) return null;
if (s.length() < 2) return s;
char[] chars = s.toCharArray();
int pre = 0;
int suf = s.length() - 1;
while (pre < suf) {
if (!isVowel(chars[pre])) {
pre++;
} else if (!isVowel(chars[suf])) {
suf--;
} else {
char temp = chars[pre];
chars[pre] = chars[suf];
chars[suf] = temp;
pre++;
suf--;
}
}
return new String(chars);
}

private static boolean isVowel(char c) {
switch (c) {
case 'a':
return true;
case 'A':
return true;
case 'e':
return true;
case 'E':
return true;
case 'i':
return true;
case 'I':
return true;
case 'o':
return true;
case 'O':
return true;
case 'u':
return true;
case 'U':
return true;
default:
return false;
}
}