My very easy understanding c++ code


  • 0
    Z
    class Solution {
    public:
        unordered_set<char> vow={'a','e','i','o','u','A','E','I','O','U'};
        string reverseVowels(string s) {
            for(auto i=s.begin(),j=s.end()-1;i<j;i++,j--)
            {
                while(vow.find(*i)==vow.end()&&i<j)//Here should add a condition to avoid a badloop
                    {
                        i++;
                    }
                while(vow.find(*j)==vow.end()&&i<j)//Here,too
                    {
                        j--;
                    }
                if(i<j)
                    {
                        char c=*i;
                        *i=*j;
                        *j=c;
                    }               
                    
            }
            return s;
        }
    };

  • 0
    Q

    Crash in VC for test case "HHHH".
    i++ will out of range.


  • 0
    Z

    You are right,Thanks for pointing it out!


  • 0
    Q

    I guess still not enough.
    1 should move your i<j condition check before find
    2 the i++ in for loop will out of range still.
    Maybe it's better to use while(i<j) to repalce for loop.


Log in to reply
 

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