Leetcode – Length of Last Word

Name: Length of Last Word
Difficulty: Easy
Description: Find the length of the last word

Example:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.
int lengthOfLastWord(string s) {
    auto i = s.end() - 1;
    while(*i == ' ') --i;

    auto j = i - 1;
    while (j >= s.begin() && *j != ' ') --j;

    return i - j;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s