Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Example 1:
Input: s = "IceCreAm"
Output: "AceCreIm"
Explanation:
The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Constraints:
1 <= s.length <= 3 * 105s consist of printable ASCII characters.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.
In this C solution, a helper function isVowel is used to determine if a character is a vowel. We use two indices to traverse the string from both ends to find vowels. When both pointers land on vowels, the vowels are swapped, and the pointers are moved inward.
C++
Java
Python
C#
JavaScript
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.
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.
In this C solution, we maintain an auxiliary buffer (string) to store vowels as we encounter them. During the second iteration of the string, we replace vowels using the stored buffer in reverse order.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n) for storing vowels separately.
| Approach | Complexity |
|---|---|
| Two Pointers Approach | Time Complexity: O(n), where n is the length of the string, as each character is processed at most twice. |
| Stack-Based Approach | Time Complexity: O(n), where n is the length of the string. |
Reverse String - 3 Ways - Leetcode 344 - Python • NeetCode • 67,202 views views
Watch 9 more video solutions →Practice Reverse Vowels of a String with our built-in code editor and test cases.
Practice on FleetCode