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)
相关推荐
LitchiCheng17 分钟前
Mujoco 基础:获取模型中所有 body 的 name, id 以及位姿
人工智能·python
老鱼说AI44 分钟前
算法基础教学第一步:数据结构
数据结构·python·算法
2301_795167201 小时前
Python 高手编程系列八:缓存
开发语言·python·缓存
闲人编程1 小时前
Django测试框架深度使用:Factory Boy与Fixture对比
数据库·python·django·sqlite·钩子·fixture·codecapsule
梅花141 小时前
基于Django房屋租赁系统
后端·python·django·bootstrap·django项目·django网站
今天没有盐1 小时前
Python数据分析实战:从超市销售到教学评估
python·pycharm·编程语言
white-persist2 小时前
【攻防世界】reverse | IgniteMe 详细题解 WP
c语言·汇编·数据结构·c++·python·算法·网络安全
霍格沃兹测试开发学社-小明2 小时前
AI来袭:自动化测试在智能实战中的华丽转身
运维·人工智能·python·测试工具·开源
@游子2 小时前
Python学习笔记-Day2
开发语言·python
wanderist.2 小时前
Linux使用经验——离线运行python脚本
linux·网络·python