c++ two pointers (O(n))


  • 0

    Using two pointers and unordered_map for checking if a letter is a vowel (time complexity: O(1)).

    string reverseVowels(string s) {
        unordered_map<char, int> m = {{'a', 0},
                                      {'e', 1},
                                      {'i', 2},
                                      {'o', 3},
                                      {'u', 3}};
        int l = 0, r = s.size() - 1;
        while (l < r) {
            while (m.find(tolower(s[l])) == m.end() && l < r) l++;
            while (m.find(tolower(s[r])) == m.end() && l < r) r--;
            if (l < r) swap(s[l++], s[r--]);
        }
        return s;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.