345. Reverse Vowels of a String

Problem:

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note:
The vowels does not include the letter "y".

 

Solutions:

class Solution {
public:
    string reverseVowels(string s) {
        unordered_set<char> vowels = {'a','e','i','o','u','A','E','I','O','U'};

        int left = 0;
        int right = s.length() - 1;

        while (left < right) {
            while (left < right && vowels.count(s[left]) == 0)  ++left;
            while (left < right && vowels.count(s[right]) == 0) --right;
            swap(s[left], s[right]);
            ++left;
            --right;
        }

        return s;
    }
};

results matching ""

    No results matching ""