-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathReverseVowelsOfString.java
48 lines (34 loc) · 1.26 KB
/
ReverseVowelsOfString.java
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
package array_string;
public class ReverseVowelsOfString {
private boolean isVowel(char ch) {
ch = Character.toLowerCase(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
public String reverseVowelsInString(String s) {
if (s == null || s.isEmpty()) return s;
char[] chars = s.toCharArray();
int left = 0, right = s.length() - 1;
while (left < right) {
while (left < right && !isVowel(chars[left])) {
left++;
}
while (left < right && !isVowel(chars[right])) {
right--;
}
if (left < right) {
char tempChar = chars[left];
chars[left] = chars[right];
chars[right] = tempChar;
left++;
right--;
}
}
return new String(chars);
}
public static void main(String[] args) {
ReverseVowelsOfString reverser = new ReverseVowelsOfString();
assert reverser.reverseVowelsInString("hello").equals("holle") : "Test case 1 failed";
assert reverser.reverseVowelsInString("leetcode").equals("leotcede") : "Test case 2 failed";
System.out.println("All tests passed!");
}
}