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)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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;
        }
    }
};
comments powered by Disqus