7-lines 4ms C++ Solution


  • 80

    Well, the basic idea is very simple. Start from the tail of s and move backwards to find the first non-space character. Then from this character, move backwards and count the number of non-space characters until we pass over the head of s or meet a space character. The count will then be the length of the last word.

    class Solution {
    public:
        int lengthOfLastWord(string s) { 
            int len = 0, tail = s.length() - 1;
            while (tail >= 0 && s[tail] == ' ') tail--;
            while (tail >= 0 && s[tail] != ' ') {
                len++;
                tail--;
            }
            return len;
        }
    };

  • 0
    D

    real simple and good


  • 0

    Hi, derekhound. You are very welcome.


  • 0
    A

    code is very clean


  • 0
    T

    Just one comment that putting tail >= 0 in the first place of while loop is important. It helps reduce checking corner cases like "".


  • 0
    K

    simple and good idea


  • 0
    I

    well, very good solution!


Log in to reply
 

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