-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc0151_reverse_words_in_a_string.py
56 lines (45 loc) · 1.52 KB
/
lc0151_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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution:
def trim_spaces(self, s: str) -> list:
left, right = 0, len(s) - 1
# remove leading spaces
while left <= right and s[left] == ' ':
left += 1
# remove trailing spaces
while left <= right and s[right] == ' ':
right -= 1
# reduce multiple spaces to single one
output = []
while left <= right:
if s[left] != ' ':
output.append(s[left])
elif output[-1] != ' ':
output.append(s[left])
left += 1
return output
def reverse(self, l: list, left: int, right: int) -> None:
while left < right:
l[left], l[right] = l[right], l[left]
left, right = left + 1, right - 1
def reverse_each_word(self, l: list) -> None:
n = len(l)
start = end = 0
while start < n:
# go to the end of the word
while end < n and l[end] != ' ':
end += 1
# reverse the word
self.reverse(l, start, end - 1)
# move to the next word
start = end + 1
end += 1
def reverseWords(self, s: str) -> str:
# converst string to char array
# and trim spaces at the same time
l = self.trim_spaces(s)
# reverse the whole string
self.reverse(l, 0, len(l) - 1)
# reverse each word
self.reverse_each_word(l)
return ''.join(l)
test = Solution()
print(test.reverseWords("the sky is blue"))