61. Tail Word Size

A text editor stores a line of text in the string s. The line consists of words made of lowercase letters, separated by one or more spaces, and it may start or end with spaces. A status bar wants to show how long the final word of the line is.

Return the number of letters in the last word of s. The line always contains at least one word. Try to solve it with a single backward scan, without splitting the string.

Example 1

Input:
s = "ship sails at dawn"
Output:
4
Explanation:

The last word is dawn, which has 4 letters.

Example 2

Input:
s = " quiet harbor "
Output:
6
Explanation:

Trailing spaces do not count; the last word is harbor, which has 6 letters.

Constraints

1 ≤ s.length ≤ 105

s contains only lowercase letters and spaces

s contains at least one word

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…