Sponsored
Sponsored
The two pointers approach involves using two indices, one starting at the beginning and the other at the end of the string. You check and swap vowels as they are encountered using these pointers, moving them inward toward each other. This method is efficient as it requires a single pass through the string, with each character processed a maximum of two times.
Time Complexity: O(n), where n is the length of the string, as each character is processed at most twice.
Space Complexity: O(1) as no additional space is used aside from variables.
1import java.util.Set;
2import java.util.HashSet;
3
4public class Solution {
5 public String reverseVowels(String s) {
6 Set<Character> vowels = new HashSet<>();
7 for (char c : "aeiouAEIOU".toCharArray()) vowels.add(c);
8 char[] arr = s.toCharArray();
9 int left = 0, right = arr.length - 1;
10 while (left < right) {
11 while (left < right && !vowels.contains(arr[left])) left++;
12 while (left < right && !vowels.contains(arr[right])) right--;
13 if (left < right) {
14 char temp = arr[left];
15 arr[left] = arr[right];
16 arr[right] = temp;
17 left++;
18 right--;
19 }
20 }
21 return new String(arr);
22 }
23}
In Java, we store vowels in a HashSet
for quick lookup. We convert the string to a character array and use two pointers to identify and swap vowels as we move toward the center of the array.
This approach uses a stack to collect all vowels in the string as they are encountered in a single pass. Then, it makes a second pass through the string to replace vowels, using the stack to supply the reversed vowels. This approach is straightforward but might not be as time efficient as the two pointers approach.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n) for storing vowels separately.
1
In this Java solution, we use a stack to collect vowels from the string, and then another iteration to replace original vowels with those popped from the stack. StringBuilder is used for efficient string manipulation.