题目链接:https://leetcode.com/problems/reverse-words-in-a-string/description/
题目描述:
Given an input string, reverse the string word by word.
要求:空间复杂度o(1)
我的实现:
def reverse_words(s):
s = s.strip(" ").split(" ")
j = len(s) - 1
for i in range(len(s)):
tmp = s[0]
for t in range(1, j+1):
s[t-1] = s[t]
s[j] = tmp
j -= 1
return s
if __name__ == "__main__":
s = input("input the str:")
print("The result is :", " ".join(reverse_words(s)))
一行python实现:
" ".join(s.strip().split()[::-1])