More elegant C++ solution, 7 lines two small loops


  • 0
    F
        int lengthOfLastWord(string s) {
            int count = 0;
            int i;
            for(i = s.size()-1; i > 0; i--)
                if(s.at(i)!=' ') break;
            for( ; i >= 0; i --)
                (s.at(i)!=' ') ? count+=1 : i=0;
            return count;
        }
    

    This does something like:
    Find the location of the last letter in the string
    Count how long the word attached to that letter is

    Why does it need to be any more complicated than that?


Log in to reply
 

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