-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-words-in-a-string.py
41 lines (32 loc) · 1.27 KB
/
reverse-words-in-a-string.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
# Problem Url: https://leetcode.com/problems/reverse-words-in-a-string, Medium
class Solution:
def reverseWords(self, s: str) -> str:
end_pointer = 0
start_pointer = 0
cum_index = 0
while start_pointer < len(s) and s[start_pointer] != "|":
if s[start_pointer].isalnum():
for i in range(start_pointer, len(s)):
if s[i].isalnum():
end_pointer = i
else:
break
if end_pointer < start_pointer:
break
new_start_pointer = len(s[start_pointer : end_pointer + 1]) + 1
s = (
s[start_pointer : end_pointer + 1]
+ "|"
+ s[0:start_pointer]
+ s[end_pointer + 1 :]
)
end_pointer = 0
cum_index += new_start_pointer
start_pointer = cum_index
start_pointer += 1
return " ".join(" ".join(s.split("|")).split())
if __name__ == "__main__":
s = Solution()
s.reverseWords("the sky is blue") # "blue is sky the"
s.reverseWords(" hello world ") # "world hello"
s.reverseWords("a good example") # "example good a"