Reverse Words in a String II
Description:
Given an input character array, reverse the array word by word. A word is defined as a sequence of non-space characters.
The input character array does not contain leading or trailing spaces and the words are always separated by a single space.
Example
Given s = “the sky is blue”,
after reversing : “blue is sky the”
Challenge
Could you do it in-place without allocating extra space?
Code:
class Solution:
"""
@param str: a string
@return: return a string
"""
def reverseWords(self, str):
# write your code here
def reverse(s):
tmp = ""
for i in range(len(s)-1, -1, -1):
tmp = tmp + s[i]
return tmp
strList = str.split(" ")
res = []
for i in strList:
res.append(reverse(i))
str2 = " ".join(res)
return reverse(str2)