Leetcode 345. Reverse Vowels of a String
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.
Input: s = “hello” Output: “holle”
Input: s = “leetcode” Output: “leotcede”
Q: Should the case of the characters be considered when identifying vowels? A: Yes, both uppercase and lowercase vowels should be reversed.
Q: Can the input string contain non-alphabetic characters? A: Yes, the input string can contain any characters, but only vowels are to be reversed.
Q: Are there constraints on the size of the input string? A: The string’s length is in a reasonably small range to avoid performance issues (like typical competitive programming constraints).
This approach ensures that we minimally traverse through the string while identifying vowels and performing swaps.
The time complexity of this approach is O(n), where n is the length of the string. This is because each character in the string is processed at most once.
Here is the C++ implementation of the strategy:
#include <iostream>
#include <unordered_set>
class Solution {
public:
std::string reverseVowels(std::string s) {
std::unordered_set<char> vowels {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
int left = 0, right = s.size() - 1;
while (left < right) {
// Move left pointer to the next vowel
while (left < right && vowels.find(s[left]) == vowels.end()) {
left++;
}
// Move right pointer to the previous vowel
while (left < right && vowels.find(s[right]) == vowels.end()) {
right--;
}
// Swap the vowels
if (left < right) {
std::swap(s[left], s[right]);
left++;
right--;
}
}
return s;
}
};
// Example usage
int main() {
Solution solution;
std::string input1 = "hello";
std::string input2 = "leetcode";
std::cout << "Reversed vowels (hello): " << solution.reverseVowels(input1) << std::endl;
std::cout << "Reversed vowels (leetcode): " << solution.reverseVowels(input2) << std::endl;
return 0;
}
This code defines a method reverseVowels
in the Solution
class, which takes a string as input and returns the string with its vowels reversed. The main function demonstrates how to use this method with example inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?