Categories:

Tags:



Problem

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

Constraints

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Solution

The problem Length of Last Word can be solved using a sliding window technique. First, rightmost index can be gained by sliding the index to the left until a non-space character is found. Next, leftmost index can be gained by sliding the index to the left until it reaches the start character or a space character is found.

Implementation

class Solution
{
  public:
    int lengthOfLastWord(string s)
    {
        int right = s.length() - 1;
        while (s[right] == ' ')
            right--;

        int left = right - 1;
        while (left >= 0 && s[left] != ' ')
            left--;

        return right - left;
    }
};