My c++ code (use a reset flag to deal with possible spaces at the end of string )


  • 2
    D
    class Solution {
    public:
        int lengthOfLastWord(const char *s) {
            int res= 0;
            bool reset = true; // reset flag to trigger the reset of res at the beginning of each new word 
            
            while(*s)
            {
                if(*(s++)== ' ')
                {reset = true;} // if space, set the reset flag
                else 
                {
                    res = reset?1:(res+1); // if reset is set, which means the current one is the first char of a new word, then set res to 1, otherwise just increase res.
                    reset = false;
                }
            }
            return res;
        }
    };

  • 0
    G
    This post is deleted!

Log in to reply
 

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