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)
相关推荐
二川bro2 分钟前
Python大语言模型调优:LLM微调完整实践指南
开发语言·python·语言模型
wa的一声哭了7 分钟前
Webase部署Webase-Web在合约IDE页面一直转圈
linux·运维·服务器·前端·python·区块链·ssh
坚持就完事了39 分钟前
蓝桥杯中Python常用的库与模块
python·算法
g***B7381 小时前
Python数据分析案例
开发语言·python·数据分析
Warren981 小时前
软件测试常见面试题
linux·python·django·flask·virtualenv·pygame·tornado
空影星1 小时前
ValiDrive:一键验证USB真实容量
python·智能手机·django·flask
喵了几个咪1 小时前
游戏字体渲染
开发语言·python·游戏
Blossom.1181 小时前
RLHF的“炼狱“突围:从PPO到DPO的工业级对齐实战
大数据·人工智能·分布式·python·算法·机器学习·边缘计算
vvoennvv1 小时前
【Python TensorFlow】CNN-BiLSTM时序预测 卷积神经网络-双向长短期记忆神经网络组合模型(附代码)
python·神经网络·cnn·tensorflow·lstm·bilstm
数据知道2 小时前
【Flask】一文掌握 Flask 基础用法
数据库·后端·python·flask·python web