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)
相关推荐
Ulyanov4 小时前
高保真单脉冲雷达导引头回波生成:Python建模与实践
开发语言·python·仿真·系统设计·单脉冲雷达
Li emily4 小时前
成功接入A股实时行情API获取实时市场数据
人工智能·python·金融·fastapi
shehuiyuelaiyuehao5 小时前
22Java对象的比较
java·python·算法
张小凡vip5 小时前
Python异步编程实战:基于async/await的高并发实现
开发语言·python
zcbk01686 小时前
不踩坑!手把手教你在 Mac 上安装 Windows(含分区/虚拟机/驱动解决方案)
python
Dev7z6 小时前
滚压表面强化过程中变形诱导位错演化与梯度晶粒细化机理的数值模拟研究
人工智能·python·算法
吴秋霖7 小时前
apple游客下单逆向分析
python·算法·逆向分析
feasibility.8 小时前
yolo11-seg在ISIC2016医疗数据集训练预测流程(含AOP调loss函数方法)
人工智能·python·yolo·计算机视觉·健康医疗·实例分割·isic2016
L念安dd9 小时前
基于 PyTorch 的轻量推荐系统框架
人工智能·pytorch·python
Liue612312319 小时前
YOLO11改进策略卷积篇使用C3k2-PPA替换YOLO11中的卷积即插即用简单高效
python