Skip to content

Commit 1a531da

Browse files
committed
Add #0058 Length of Last Word
1 parent 722ebbf commit 1a531da

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

#0058 Length of Last Word.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
def lengthOfLastWord(self, s: str) -> int:
3+
"""
4+
Given a string s consisting of some words separated by spaces, return the length
5+
of the last word in the string. A word is a maximal substring consisting of non-space characters only.
6+
7+
Args:
8+
s (str): The input string.
9+
10+
Returns:
11+
int: The length of the last word in the string.
12+
"""
13+
words = s.split(" ") # Split the string into words based on spaces
14+
i = len(words) - 1 # Initialize index to the last word
15+
16+
# Traverse backwards to find the last non-empty word
17+
while not words[i]:
18+
i -= 1
19+
20+
return len(words[i]) # Return the length of the last non-empty word

0 commit comments

Comments
 (0)