LeetCode: Reverse Vowels of a String

LeetCode: Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Given s = “hello”, return “holle”.

Example 2:

Given s = “leetcode”, return “leotcede”.

Note:

The vowels does not include the letter “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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Solution {
private Set<Character> vowels = new HashSet<Character>() {{
add('A');
add('a');
add('E');
add('e');
add('I');
add('i');
add('O');
add('o');
add('U');
add('u');

}};

public String reverseVowels(String s) {

if (s == null || s.length() < 2) {
return s;
}
char[] chars = s.toCharArray();
int l = 0;
int r = s.length() - 1;
while (l < r) {
while (l < r) {
if (vowels.contains(chars[l])) {
break;
} else {
l++;
}
}
while (l < r) {
if (vowels.contains(chars[r])) {
break;
} else {
r--;
}
}

if (l < r) {
char tmp = chars[l];
chars[l] = chars[r];
chars[r] = tmp;
l++;
r--;
}
}
StringBuilder sb = new StringBuilder();
for(char c : chars){
sb.append(c);
}
return sb.toString();
}
}