C++ Solution using Vector


  • 0
    F
    string reverseVowels(string s) {
            if(s.length()<=1)
                return s;
            vector<char> vec {'a','e','i','o','u','A','E','I','O','U'};     
            for(int i=0, j=s.length()-1;i<j;){
                if(find(vec.begin(),vec.end(),s[i]) ==vec.end()){
                    i++;              
                }
                if(find(vec.begin(),vec.end(),s[i]) !=vec.end()){
                    if(find(vec.begin(),vec.end(),s[j]) !=vec.end()){
                        swap(s[i],s[j]);
                        i++;
                        j--;
                    }
                    else
                        j--;
                }
                
            }
            return s;
    

  • 0
    F

    Improved version: time reduces to 9ms from 12ms

    string reverseVowels(string s) {
            if(s.length()<=1)
                return s;
            vector<char> vec {'a','e','i','o','u','A','E','I','O','U'};     
            for(int i=0, j=s.length()-1;i<j;){
                while(i<j && find(vec.begin(),vec.end(),s[i]) ==vec.end()){
                    i++;              
                }
                while(i<j && find(vec.begin(),vec.end(),s[j]) ==vec.end()){
                    j--;
                }
                if(i>j) break;
                swap(s[i++],s[j--]);
            }
            return s;
        }
    

Log in to reply
 

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