LeetCode 151 Reverse Words in a String 解题思路和python代码

题目:

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.

Example 1:

Input: s = "the sky is blue"

Output: "blue is sky the"

Example 2:

Input: s = " hello world "

Output: "world hello"

Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good example"

Output: "example good a"

Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints:

1 <= s.length <= 104

s contains English letters (upper-case and lower-case), digits, and spaces ' '.

There is at least one word in s.

Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

解题思路:

首先,去掉前后空格。

然后,利用split()将string按空格分割成一个单词list。

接着,反转单词list。

最后,将反转后的单词list用空格连接起来。

例子:
" hello world ",先去掉前后空格得到 ["hello", "world"],反转后是 ["world", "hello"],输出 "world hello"

python 复制代码
class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        words = s.strip().split()
        reverse_words = words[::-1]
        return ' '.join(reverse_words)
相关推荐
李可以量化几秒前
Redis Client 从了解到精通(二)下:String 类型进阶操作全解
redis·git·python·量化交易·qmt
leisoo80978 分钟前
财报舞弊预警系统实战用Python挖掘应收存货异常因子 IG50免费开源股票数据API接口
开发语言·python
cui_ruicheng1 小时前
LangChain 应用开发(十二):Agent 中间件与内置中间件
人工智能·python·中间件·langchain
zx_741484811 小时前
【Python 入门】Python 正则表达式零基础讲解:基础语法 + 元字符 + 常用案例
python·正则表达式
weixin199701080161 小时前
《大促护航:电商API限流与降级,双11峰值500万调用的架构复盘》(附Python源码)
python·架构·wpf
2601_957883841 小时前
2026年8月:华硕笔记本维修相关信息
python·电脑
lzqrzpt1 小时前
临沂LED驱动电源工程选型与直销工厂评估标准解析
python·单片机·嵌入式硬件
老郑聊AI业财智造1 小时前
给大模型装上“金融之眼”:Kronos-Report的量化预测架构与技术全景剖析
人工智能·python·深度学习·语言模型·金融·架构·软件工程
问天_观心2 小时前
深入学习Transformer(一)
人工智能·python·深度学习·神经网络·学习·transformer
雷帝木木2 小时前
DVC数据版本控制实战:让训练数据像代码一样可追溯
人工智能·python·深度学习·机器学习