Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 123ae67

Browse files
Length of Last Word
1 parent c8260cb commit 123ae67

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

‎58-length-of-last-word.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/length-of-last-word/
3+
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
4+
A word is a maximal substring consisting of non-space characters only.
5+
6+
Example 1:
7+
Input: s = "Hello World"
8+
Output: 5
9+
Explanation: The last word is "World" with length 5.
10+
11+
Example 2:
12+
Input: s = " fly me to the moon "
13+
Output: 4
14+
Explanation: The last word is "moon" with length 4.
15+
16+
Example 3:
17+
Input: s = "luffy is still joyboy"
18+
Output: 6
19+
Explanation: The last word is "joyboy" with length 6.
20+
21+
Constraints:
22+
1 <= s.length <= 104
23+
s consists of only English letters and spaces ' '.
24+
There will be at least one word in s.
25+
"""
26+
class Solution:
27+
def lengthOfLastWord(self, s: str) -> int:
28+
return len(s.split()[-1])
29+
30+
31+
class Solution1:
32+
def lengthOfLastWord(self, s: str) -> int:
33+
s = s.split(" ")
34+
35+
index = len(s) - 1
36+
while index >= 0:
37+
if s[index] != "":
38+
return len(s[index])
39+
index -= 1
40+
41+
42+
class Solution2:
43+
def lengthOfLastWord(self, s: str) -> int:
44+
index = len(s) - 1
45+
count = 0
46+
flag = False
47+
while index >= 0:
48+
if flag:
49+
if s[index] == ' ':
50+
return count
51+
count += 1
52+
elif s[index] != ' ':
53+
flag = True
54+
count += 1
55+
56+
index -= 1
57+
58+
return count

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /