-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathReverseVowels.java
More file actions
39 lines (33 loc) · 805 Bytes
/
ReverseVowels.java
File metadata and controls
39 lines (33 loc) · 805 Bytes
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
import java.util.*;
/*Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Note:
The vowels does not include the letter "y".
*/
class ReverseVowels {
public String reverseVowels(String s) {
if (s == null || s.length() < 2) {
return s;
}
List<Character> vowels = new ArrayList<>();
List<Character> arr = Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
for (char c : s.toCharArray()) {
if (arr.contains(c)) {
vowels.add(c);
}
}
Collections.reverse(vowels);
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (arr.contains(c)) {
sb.append(vowels.get(0));
vowels.remove(0);
} else {
sb.append(c);
}
}
return sb.toString();
}
}