Skip to content

Commit b528c6a

Browse files
committed
solved Problem 58 in Python
1 parent 0b4f2bd commit b528c6a

File tree

6 files changed

+56
-0
lines changed

6 files changed

+56
-0
lines changed

python/questions_001_100/question_058/__init__.py

Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Length of Last Word
2+
3+
# Problem 58
4+
# Given a string s consisting of some words separated by some number of 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+
class Solution:
25+
def length_of_last_word(self, s: str) -> int:
26+
length = 0
27+
isWord = False
28+
for i in range(len(s)):
29+
char = s[len(s) - 1 - i]
30+
if char == ' ':
31+
if isWord:
32+
return length
33+
else:
34+
continue
35+
else:
36+
isWord = True
37+
length += 1
38+
return length
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import unittest
2+
from . import length_of_last_word
3+
4+
5+
class TestLengthOfLastWord(unittest.TestCase):
6+
def test_length_of_last_word(self):
7+
self.assertEqual(
8+
length_of_last_word.Solution().length_of_last_word('Hello World'), 5)
9+
self.assertEqual(
10+
length_of_last_word.Solution().length_of_last_word(
11+
' fly me to the moon '), 4)
12+
self.assertEqual(
13+
length_of_last_word.Solution().length_of_last_word(
14+
'luffy is still joyboy'), 6)
15+
16+
17+
if __name__ == '__main__':
18+
unittest.main()

0 commit comments

Comments
 (0)