Reverse Vowels of a String

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

Example 1: Given s = "hello", return "holle".

Example 2: Given s = "leetcode", return "leotcede".

class Solution {
public:
    string reverseVowels(string s) {
        if(s.size() < 2) return s;

        unordered_set<char> vowels;
        vowels.insert('a');
        vowels.insert('A');
        vowels.insert('o');
        vowels.insert('O');
        vowels.insert('i');
        vowels.insert('I');
        vowels.insert('e');
        vowels.insert('E');
        vowels.insert('u');
        vowels.insert('U');


        int st = 0, en = s.size() - 1;

        while(st < en){
            while(st < en && vowels.find(s[st]) == vowels.end() ) {
                st++;
            }

            while(st<en && vowels.find(s[en]) == vowels.end() ){
                en--;
            }
            if(st < en) swap(s[st], s[en]);
            st++;
            en--;
        }
        return s;
    }
};

results matching ""

    No results matching ""