length-of-last-word.sh — zsh
strings

Return the number of characters in the final word of s. A word is a maximal run of non-space characters. Ignore trailing spaces and return 0 when no word exists.

Input / output

  • Input: s: string
  • Output: integer length

Examples

  1. "Hello World" returns 5.
  2. " fly me to the moon " returns 4.

Constraints

  • 0 <= s.length <= 100,000
  • The separator is the ASCII space character.

Follow-up Can you solve it with one reverse scan and no substring allocation?

Examples
Example 1
Input: s = "Hello World"
Output: 5
Example 2
Input: s = " "
Output: 0
Example 3
Input: s = "a "
Output: 1
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.