-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreverse_string.py
More file actions
executable file
·38 lines (26 loc) · 951 Bytes
/
Copy pathreverse_string.py
File metadata and controls
executable file
·38 lines (26 loc) · 951 Bytes
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
"""
Given an input string, reverse the string word by word.
Example:
Given s = "the sky is blue",
return "blue is sky the".
A sequence of non-space characters constitutes a word.
Your reversed string should not contain leading or trailing spaces, even if it is present in the input string.
If there are multiple spaces between words, reduce them to a single space in the reversed string.
"""
class Solution:
# @param A : string
# @return string
def reverseWords(self, str):
string = list(reversed(str))
start = 0
end = 0
for end in range(len(string) + 1):
if end == len(string) or string[end] == " ":
string[start:end] = reversed(string[start:end])
start = end + 1
return "".join(string)
s = Solution()
input = "the sky is blue"
output = "blue is sky the"
assert s.reverseWords(input) == output, "Houston, we have a problem!"
print "Success!"