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)
相关推荐
shut up32 分钟前
LangChain - 如何使用阿里云百炼平台的Qwen-plus模型构建一个桌面文件查询AI助手 - 超详细
人工智能·python·langchain·智能体
宝贝儿好1 小时前
【python】第五章:python-GUI编程
python·pyqt
闲人编程2 小时前
从多个数据源(CSV, Excel, SQL)自动整合数据
python·mysql·数据分析·csv·存储·数据源·codecapsule
B站_计算机毕业设计之家2 小时前
推荐系统实战:python新能源汽车智能推荐(两种协同过滤+Django 全栈项目 源码)计算机专业✅
大数据·python·django·汽车·推荐系统·新能源·新能源汽车
茯苓gao2 小时前
Django网站开发记录(一)配置Mniconda,Python虚拟环境,配置Django
后端·python·django
Full Stack Developme2 小时前
Python Redis 教程
开发语言·redis·python
码界筑梦坊2 小时前
267-基于Django的携程酒店数据分析推荐系统
python·数据分析·django·毕业设计·echarts
Cherry Zack2 小时前
Django视图进阶:快捷函数、装饰器与请求响应
后端·python·django
qq_4924484463 小时前
Jmeter设置负载阶梯式压测场景(详解教程)
开发语言·python·jmeter
lianyinghhh3 小时前
瓦力机器人-舵机控制(基于树莓派5)
人工智能·python·自然语言处理·硬件工程