leetcode ReverseVowelsofaString
z
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
import java.util.HashMap;
import java.util.HashSet;

public class ReverseVowelsofaString {
/**
* Write a function that takes a string as input and reverse only the vowels of a string.
* <p>
* Example 1:
* <p>
* Input: "hello"
* Output: "holle"
* Example 2:
* <p>
* Input: "leetcode"
* Output: "leotcede"
*/
public String reverseVowels(String s) {
HashSet<Character> vowels = new HashSet<>();
char[] sc = s.toCharArray();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (vowels.contains(sc[left]) && vowels.contains(sc[right])) {
char t = sc[left];
sc[left] = sc[right];
sc[right] = t;
}
if (!vowels.contains(sc[left])) left++;
if (!vowels.contains(sc[right])) right--;
}
StringBuilder sb = new StringBuilder();
for (char c: sc){
sb.append(c);
}
return sb.toString();
}
}