-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
37 lines (30 loc) · 958 Bytes
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 58. Length of Last Word
class Solution:
# Time complexity: O(s) where s = len(s), Space complexity: O(1)
def lengthOfLastWord(self, s: str) -> int:
# return self.noBrainer(s)
left = 0
right = 0
# "hello "
#. ^
# ^
# "hello world"
# " "
# ""
# "hello"
wordLength = 0
while left < len(s) and right < len(s):
if s[right] == ' ':
right += 1
left = right
else:
wordLength = right - left + 1
right += 1
return wordLength
def noBrainer(self, s: str) -> int:
return len(s.strip().split(' ')[-1])
print(Solution().lengthOfLastWord("hello "))
print(Solution().lengthOfLastWord(""))
print(Solution().lengthOfLastWord("hello world"))
print(Solution().lengthOfLastWord("hello"))
print(Solution().lengthOfLastWord(" "))