C++ easy understanding solution


  • 14
    S
    class Solution {
    public:
        string reverseVowels(string s) {
            int dict[256] = {0};
            dict['a'] = 1, dict['A'] = 1;
            dict['e'] = 1, dict['E'] = 1;
            dict['i'] = 1, dict['I'] = 1;
            dict['o'] = 1, dict['O'] = 1;
            dict['u'] = 1, dict['U'] = 1;
            int start = 0, end = (int)s.size() - 1;
            while(start < end){
                while(start < end && dict[s[start]] == 0) start++;
                while(start < end && dict[s[end]] == 0) end--;
                swap(s[start],s[end]);
                start++;end--;
            }
            return s;
        }
    };

  • 1
    D

    It's nice to have a dict to check for vowel.


  • 7
    W
    string reverseVowels(string s) {
        set<char> vowels = {'a','e','i','o','u','A','E','I','O','U'};
        int i= 0, j = s.size()-1;
        while(i<j){
            while(vowels.find(s[i])==vowels.end()) i++;
            while(vowels.find(s[j])==vowels.end()) j--;
            if(i>=j) break;
            swap(s[i],s[j]);
            i++;
            j--;
        }
        return s;
    }
    

    I use set for look up. Since set::find() has a complexity of log(n) (n is the size of the set), and we only have 10 elements in the set, we can save some space and implementation redundancies.


  • 2
    S

    You could use unordered_set, unordered_set::find() has a O(1) time complexity.


  • 0

    @sxycwzwzq I agree with what you said.
    But when I test it on leetcode, "set" takes me 12 ms, while "unordered_set" takes me 22 ms. Does any one know the reason?


Log in to reply
 

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