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

  • 0
        int lengthOfLastWord(string s) {
            int count = 0;
            int i;
            for(i = s.size()-1; i > 0; i--)
                if(!=' ') break;
            for( ; i >= 0; 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.