Skip to content

Commit 8e71623

Browse files
docs: 58
1 parent b7de3a2 commit 8e71623

File tree

1 file changed

+7
-33
lines changed

1 file changed

+7
-33
lines changed

explanations/58/en.md

Lines changed: 7 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,26 @@
1-
# 58. Length of Last Word
2-
3-
**Difficulty:** Easy
4-
**Link:** https://leetcode.com/problems/length-of-last-word/
5-
6-
## Problem Description
7-
81
Given a string `s` consisting of words and spaces, return *the length of the **last** word in the string.*
92

103
A **word** is a maximal substring consisting of non-space characters only.
114

125
**Example 1:**
13-
```
6+
7+
```sh
148
Input: s = "Hello World"
159
Output: 5
1610
Explanation: The last word is "World" with length 5.
1711
```
1812

1913
**Example 2:**
20-
```
14+
15+
```sh
2116
Input: s = " fly me to the moon "
2217
Output: 4
2318
Explanation: The last word is "moon" with length 4.
2419
```
2520

2621
**Example 3:**
27-
```
22+
23+
```sh
2824
Input: s = "luffy is still joyboy"
2925
Output: 6
3026
Explanation: The last word is "joyboy" with length 6.
@@ -73,7 +69,7 @@ Let's break down the solution step by step:
7369
**Example walkthrough:**
7470
Let's trace through the second example:
7571

76-
```
72+
```sh
7773
s = " fly me to the moon "
7874

7975
Step 1: Start from end
@@ -97,27 +93,5 @@ Result: Return 4
9793

9894
> **Note:** The key insight is to work backwards from the end of the string. This approach is efficient because we only need to traverse the string once from the end, and we can handle trailing spaces naturally.
9995
100-
### Solution
101-
102-
```python
103-
class Solution:
104-
def lengthOfLastWord(self, s: str) -> int:
105-
# Start from the end of the string
106-
i = len(s) - 1
107-
length = 0
108-
109-
# Skip trailing spaces
110-
while i >= 0 and s[i] == ' ':
111-
i -= 1
112-
113-
# Count characters of the last word
114-
while i >= 0 and s[i] != ' ':
115-
length += 1
116-
i -= 1
117-
118-
# Return the length of the last word
119-
return length
120-
```
121-
12296
**Time Complexity:** O(n) - we visit each character at most once
12397
**Space Complexity:** O(1) - we only use a constant amount of extra space

0 commit comments

Comments
 (0)