Skip to content

Commit d60d4ff

Browse files
solves reverse vowels of a string
1 parent 32a663f commit d60d4ff

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/ReverseVowelsOfString.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.ArrayList;
2+
import java.util.HashSet;
3+
import java.util.List;
4+
import java.util.Set;
5+
6+
public class ReverseVowelsOfString {
7+
private static final Set<Character> VOWELS = new HashSet<>();
8+
9+
static {
10+
VOWELS.add('a');
11+
VOWELS.add('e');
12+
VOWELS.add('i');
13+
VOWELS.add('o');
14+
VOWELS.add('u');
15+
VOWELS.add('A');
16+
VOWELS.add('E');
17+
VOWELS.add('I');
18+
VOWELS.add('O');
19+
VOWELS.add('U');
20+
}
21+
22+
public static String reverseVowels(String string) {
23+
List<Character> vowels = getVowels(string);
24+
StringBuilder result = new StringBuilder();
25+
for (int index = 0, j = vowels.size() - 1 ; index < string.length() ; index++) {
26+
char character = string.charAt(index);
27+
result.append(isVowel(character) ? vowels.get(j--) : character);
28+
}
29+
return result.toString();
30+
}
31+
32+
private static boolean isVowel(char character) {
33+
return VOWELS.contains(character);
34+
}
35+
36+
private static List<Character> getVowels(String string) {
37+
List<Character> vowels = new ArrayList<>();
38+
for (int index = 0 ; index < string.length() ; index++) {
39+
char character = string.charAt(index);
40+
if (isVowel(character)) {
41+
vowels.add(character);
42+
}
43+
}
44+
return vowels;
45+
}
46+
}

0 commit comments

Comments
 (0)