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

转载自Leet Code

题目描述

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

示例 1: >输入:"hello" >输出:"holle"

示例 2: >输入:"leetcode" >输出:"leotcede"

提示

  • 元音字母不包含字母 "y"

我的代码

\(T(N) = O(N)\), \(S(N) = O(1)\)

{.line-numbers}
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
class MySolution345 
{
HashSet<Character> Vowel;
public String reverseVowels(String s)
{
Vowel = new HashSet();
Vowel.add('a'); Vowel.add('e'); Vowel.add('i'); Vowel.add('o'); Vowel.add('u');
Vowel.add('A'); Vowel.add('E'); Vowel.add('I'); Vowel.add('O'); Vowel.add('U');
StringBuilder sb = new StringBuilder(s);

for (int i=0,j=s.length()-1; i<j; )
{
if (!Vowel.contains(s.charAt(i)))
{
i++; continue;
}
if (!Vowel.contains(s.charAt(j)))
{
j--; continue;
}
char tmp = s.charAt(i);
sb.setCharAt(i, s.charAt(j));
sb.setCharAt(j, tmp);
i++; j--;
}
return sb.toString();
}
}