Skip to content

Commit 2855fb0

Browse files
committed
[NEW] 58. Length of Last Word
1 parent a1969b2 commit 2855fb0

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

58.length_of_last_word.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from typing import List
2+
3+
"""
4+
Given a string s consisting of words and spaces, return the length of the last word in the string.
5+
6+
A word is a maximal substring consisting of non-space characters only.
7+
8+
Example 1:
9+
Input: s = "Hello World"
10+
Output: 5
11+
Explanation: The last word is "World" with length 5.
12+
13+
Example 2:
14+
Input: s = " fly me to the moon "
15+
Output: 4
16+
Explanation: The last word is "moon" with length 4.
17+
18+
Example 3:
19+
Input: s = "luffy is still joyboy"
20+
Output: 6
21+
Explanation: The last word is "joyboy" with length 6.
22+
23+
24+
Constraints:
25+
1 <= s.length <= 10⁴
26+
s consists of only English letters and spaces ' '.
27+
There will be at least one word in s.
28+
"""
29+
30+
class Solution:
31+
def lengthOfLastWord(self, s: str) -> int:
32+
# Remove unnecessary spaces
33+
s: str = s.strip()
34+
35+
# Split by string by spaces to get the words
36+
words: List[str] = s.split(' ')
37+
38+
# Return the length of last word
39+
return len(words[-1])

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ In this repository, you will find a wide range of LC solutions, including the fo
2121

2222
- Strings:
2323

24+
- **58.Length of Last Word**: [link](58.length_of_last_word.py)
2425
- **293.Is Subsequence**: [link](293.is_subsequence.py)
2526
- **250.Isomorphic Strings**: [link](250.isomorphic_strings.py)
2627

0 commit comments

Comments
 (0)