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)
相关推荐
Sylvia33.11 分钟前
足球数据接口开发实战:如何用火星数据API盘活赛事应用
java·服务器·开发语言·数据库·python
lupai18 分钟前
身份证二要素实名认证 API 落地应用指南
python
cxr82829 分钟前
大语言模型上下文缓存命中率测试全场景清单
人工智能·python·算法·缓存·语言模型·自然语言处理·llm
某林21233 分钟前
大模型边缘部署到底层硬件闭环
python·架构·机器人·硬件架构·ros2
LadenKiller1 小时前
最新量化软件选择,先按能力判断表达生成和执行
人工智能·python
退休倒计时1 小时前
【每日一题】LeetCode 287. 寻找重复数 TypeScript
算法·leetcode·typescript
iuu_star2 小时前
Python大模型智能学习平台——设计与实现(AI教学系统)
大数据·人工智能·python·学习
天才测试猿2 小时前
如何封装自动化测试框架?
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
overmind2 小时前
oeasy Python 102 集合_运算_交集_并集_差集_对称差集
开发语言·python
爱吃提升2 小时前
Python自动驾驶图像识别完整实战教程(OpenCV+YOLOv8,附可直接运行源码)
python·opencv·自动驾驶