LC 58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word in the string.

If the last word does not exist, return 0.


Keep a counter, lastWordLen, for the length of the last word encounter. It is initialized at 0. We also need a counter to determine the current word len.

Then we iterate through the list, if we see a non-whitespace, we increment the curWordLen by 1.

If we see a whitespace

  1. if curWordLen is 0, the previous letter is also white space and it won’t constitute a word, so we do nothing
  2. else, we update lastWordLen and set curWordLen to 0.

Edge case

Empty input

since lastWordLen is 0 and will never be updated, its good.

Single word

The for loop only update lastwordLen when it sees a white space. If the input is single word, we need to check lastWordLen and update.

    int lengthOfLastWord(string s) {
        int lastWordLen = 0;
        int lenCtr = 0;
        for (int i = 0; i < s.size(); i ++){
            if (s[i] != ' '){
                lenCtr += 1;
                if (lenCtr != 0){
                    lastWordLen = lenCtr;    

                lenCtr = 0;
        if(lenCtr != 0)
            lastWordLen = lenCtr;
        return lastWordLen;


Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see