345. Reverse Vowels of a String
1. Description
Write a function that takes a string as input and reverse only the vowels of a string.
2. Example
Example 1
Input: “hello”
Output: “holle”
Example 2
Input: “leetcode”
Output: “leotcede”
3. Note
- The vowels does not include the letter “y”.
4. Solutions
Two Pointers
n = s.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution {
public:
string reverseVowels(string s) {
for (int left = 0, right = s.size() - 1; left < right; ++left, --right) {
while (left < right && !is_vowel(s[left])) {
++left;
}
while (left < right && !is_vowel(s[right])) {
--right;
}
swap(s[left], s[right]);
}
return s;
}
private:
bool is_vowel(const char &letter) {
switch (letter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
default:
return false;
}
}
};