-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_151.py
46 lines (39 loc) · 1.03 KB
/
leetcode_151.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
38
39
40
41
42
43
44
45
46
def main(s: str):
sLen = len(s)
# remove trailing and leading spaces
left = 0
right = sLen - 1
while left < right:
if s[left] != " " and s[right] != " ":
break
elif s[left] != " ":
right -= 1
elif s[right] != " ":
left += 1
else:
left += 1
right -= 1
s = s[left: right + 1]
sLen = len(s)
# loop through the newS
i = 0
result = ""
currentWord = ""
while i < sLen:
if s[i] != " ":
currentWord += s[i]
if i == sLen - 1:
if result == "":
result = currentWord
else:
result = f"{currentWord} {result}"
currentWord = ""
elif s[i] == " " and currentWord != "":
if result == "":
result = currentWord
else:
result = f"{currentWord} {result}"
currentWord = ""
i += 1
return result
main("a good example")