/58. Length of Last Word

58. Length of Last Word

Easy
Strings58.4% acceptance

Given a string input_str consisting of English letters and spaces, return the length of the last contiguous sequence of non-space characters (word) in input_str. A word is defined as a maximal substring of consecutive non-space characters.

Example 1

Input: data science is fun

Output: 3

Explanation: The last word is fun, which has length 3.

Example 2

Input: python programming

Output: 11

Explanation: The last word is programming, which has length 11.

Example 3

Input: algorithm

Output: 9

Explanation: The last word is algorithm, which has length 9.

Constraints

  • 1 <= len(input_str) <= 10_000
  • input_str consists only of uppercase and lowercase English letters and spaces ( )
  • There is at least one word in input_str
Python (current runtime)

Case 1

Input: 'machine learning rocks'

Expected: 5

Case 2

Input: ' hello world '

Expected: 5

Case 3

Input: 'openai'

Expected: 6

Case 4

Input: 'deep neural networks '

Expected: 8

Case 5

Input: ' a b c d e f g '

Expected: 1