Simple 3ms C++ Solution Using Reverse Iterators


  • 0
    M
    int lengthOfLastWord(string s) {
            if(s.empty())
                return 0;
            int count = 0;
            //get (reversed) iterator to last element (ie. element before s.end()), 
            //and if it is white space, advance it till you get to the first non-whitespace character.
            auto it = s.crbegin();
            while (*it == ' ')
                it++;
            for( ; it != s.crend() && *it != ' '; ++it)
                count++;
            return count;
    

Log in to reply
 

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