Leetcode
  • Leetcode
  • 1. Two Sum
  • 7. Reverse Integer
  • 9. Palindrome Number
  • 13. Roman to Integer
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 35. Search Insert Position
  • 53. Maximum Subarray
  • 58. Length of Last Word
  • 66. Plus One
  • 876. Middle of the Linked List
  • 67. Add Binary
  • 69. Sqrt(x)
  • 83. Remove Duplicates from Sorted List
  • 14. Longest Common Prefix
  • 70. Climbing Stairs
  • 100. Same Tree
  • 101. Symmetric Tree
  • 104. Maximum Depth of Binary Tree
  • Untitled
Powered by GitBook
On this page

58. Length of Last Word

Previous53. Maximum SubarrayNext66. Plus One

Last updated 6 years ago

/

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5

Solution:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        container = []
        flush = 0
        for i in range(len(s)):
            if s[i] == ' ':
                flush = 1
            else:
                if flush == 1:
                    container = []
                    flush = 0
                container.append(s[i])
        return len(container)
https://leetcode.com/problems/length-of-last-word
description/