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)
相关推荐
会飞的拖把15 分钟前
Python 多任务编程:并发、进程、线程与线程安全详解
开发语言·python
2601_9563198826 分钟前
看到“2026年量化学习”时,交易想法要先拆成条件和动作
人工智能·python
大模型码小白1 小时前
Harness Engineering 驾驭工程:从使用到项目实战
大数据·数据库·人工智能·python·spring
程序员小远1 小时前
自动化测试用例编写实例详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
Tisfy1 小时前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
2601_962295582 小时前
Python UI自动化测试用例脚本编写指南
python·测试用例·uiautomator2·ui自动化测试·脚本编写
重生之小比特2 小时前
【Java SE】数据类型与变量
java·开发语言·python
find1star2 小时前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
LadenKiller2 小时前
先分清阶段,再让工具帮量化学习
人工智能·python
WeiXin_DZbishe2 小时前
基于springboot大学生提问箱系统-计算机毕设【课程设计】72593
javascript·vue.js·spring boot·vscode·python·node.js·php