Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created September 15, 2020 10:57
Show Gist options
  • Save kuntalchandra/bc8c66b8ec0749ab7ac7870e1450ae4d to your computer and use it in GitHub Desktop.
Save kuntalchandra/bc8c66b8ec0749ab7ac7870e1450ae4d to your computer and use it in GitHub Desktop.
Length of Last Word
"""
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word
(last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.
Example:
Input: "Hello World"
Output: 5
"""
class Solution:
def lengthOfLastWord(self, s: str) -> int:
if not s:
return 0
s = s.strip()
res = 0
n = len(s) - 1
for i in range(n, -1, -1):
if s[i] == " ":
return res
res += 1
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment