题目链接: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])
本文介绍了一道LeetCode上的经典题目——翻转字符串中的单词,并提供了一种Python实现方法。该方法首先去除字符串首尾空白并按空格拆分单词,然后使用Python内置功能[::-1]进行单词翻转,最后将单词重新组合成完整字符串。
1万+

被折叠的 条评论
为什么被折叠?



