-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path151_reverse_words_in_a_string.py
50 lines (40 loc) · 1.3 KB
/
151_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
"""
151. Reverse Words in a String
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters.
The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated
by a single space.
Note that s may contain leading or trailing spaces or multiple
spaces between two words. The returned string should only have
a single space separating the words. Do not include any extra spaces.
"""
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
# Split into a list of words
words = s.split()
# Reverse the order
revresed_words = words[::-1]
# Join the words from the list
result = ' '.join(revresed_words)
return result
s = Solution()
# Case 1
output = s.reverseWords(s="the sky is blue")
expected = "blue is sky the"
print(f"Result: {output}, Expected: {expected}")
assert output == expected
# Case 2
output = s.reverseWords(s=" hello world ")
expected = "world hello"
print(f"Result: {output}, Expected: {expected}")
assert output == expected
# Case 1
output = s.reverseWords(s="a good example")
expected = "example good a"
print(f"Result: {output}, Expected: {expected}")
assert output == expected