We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 722ebbf commit 1a531daCopy full SHA for 1a531da
#0058 Length of Last Word.py
@@ -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