You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a string `s` consisting of words and spaces, return *the length of the **last** word in the string.*
9
2
10
3
A **word** is a maximal substring consisting of non-space characters only.
11
4
12
5
**Example 1:**
13
-
```
6
+
7
+
```sh
14
8
Input: s = "Hello World"
15
9
Output: 5
16
10
Explanation: The last word is "World" with length 5.
17
11
```
18
12
19
13
**Example 2:**
20
-
```
14
+
15
+
```sh
21
16
Input: s = " fly me to the moon "
22
17
Output: 4
23
18
Explanation: The last word is "moon" with length 4.
24
19
```
25
20
26
21
**Example 3:**
27
-
```
22
+
23
+
```sh
28
24
Input: s = "luffy is still joyboy"
29
25
Output: 6
30
26
Explanation: The last word is "joyboy" with length 6.
@@ -73,7 +69,7 @@ Let's break down the solution step by step:
73
69
**Example walkthrough:**
74
70
Let's trace through the second example:
75
71
76
-
```
72
+
```sh
77
73
s = " fly me to the moon "
78
74
79
75
Step 1: Start from end
@@ -97,27 +93,5 @@ Result: Return 4
97
93
98
94
> **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.
99
95
100
-
### Solution
101
-
102
-
```python
103
-
classSolution:
104
-
deflengthOfLastWord(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 >=0and s[i] =='':
111
-
i -=1
112
-
113
-
# Count characters of the last word
114
-
while i >=0and s[i] !='':
115
-
length +=1
116
-
i -=1
117
-
118
-
# Return the length of the last word
119
-
return length
120
-
```
121
-
122
96
**Time Complexity:** O(n) - we visit each character at most once
123
97
**Space Complexity:** O(1) - we only use a constant amount of extra space
0 commit comments