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.
1#include <iostream>
2#include <unordered_set>
3using namespace std;
4
5string reverseVowels(string s) {
6 unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
7 int left = 0, right = s.size() - 1;
8 while (left < right) {
9 while (left < right && vowels.find(s[left]) == vowels.end()) left++;
10 while (left < right && vowels.find(s[right]) == vowels.end()) right--;
11 if (left < right) {
12 swap(s[left++], s[right--]);
13 }
14 }
15 return s;
16}
This C++ solution uses a unordered_set
to store vowels. Two pointers are used to traverse the string from both ends, swapping vowels when found. This reduces the overhead of checking whether a character is a vowel.
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
This JavaScript solution creates an Array to hold vowels and then replaces vowels in the string from this array. The pop operation ensures that vowels are placed correctly in reversed order.