LeetCode 58. Length of Last Word



Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

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

Example 1:

Input: s = "Hello World"
Output: 5

Example 2:

Input: s = " "
Output: 0


  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.


Split the string and find the length of the last word. If the string can’t be spitted, return 0.

Python Solution

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        if not s:
            return 0
        words = s.split()
        if not words:
            return 0
        last_word = words[-1]
        return len(last_word)
  • Time Complexity: O(N).
  • Space Complexity: O(1).

Leave a Reply

Your email address will not be published. Required fields are marked *