-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReverseVowelsOfString.java
More file actions
39 lines (33 loc) · 969 Bytes
/
ReverseVowelsOfString.java
File metadata and controls
39 lines (33 loc) · 969 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
package string;
import java.util.Set;
/**
* Description: https://leetcode.com/problems/reverse-vowels-of-a-string
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class ReverseVowelsOfString {
public String reverseVowels(String s) {
Set<Character> vowels = Set.of('a', 'e', 'i', 'u', 'o', 'A', 'E', 'I', 'U', 'O');
int left = 0;
int right = s.length() - 1;
char[] input = s.toCharArray();
while (left < right) {
if (!vowels.contains(input[left])) {
left++;
} else if (!vowels.contains(input[right])) {
right--;
} else {
swap(input, left, right);
left++;
right--;
}
}
return new String(input);
}
private void swap(char[] input, int i, int j) {
char tmp = input[i];
input[i] = input[j];
input[j] = tmp;
}
}