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)
相关推荐
科研小达人几秒前
ChatGPT进行翻译
开发语言·python·chatgpt
joker_zsl12 分钟前
Django makemigrations时出现TypeError: ‘module‘ object is not iterable
后端·python·django
子墨77714 分钟前
django 模版语言
python
sjsjs1125 分钟前
【动态规划-最长公共子序列(LCS)】力扣97. 交错字符串
算法·leetcode·动态规划
福楠38 分钟前
[LeetCode] 143. 重排链表
数据结构·c++·算法·leetcode·链表
大二转专业41 分钟前
408算法题leetcode--第29天
考研·算法·leetcode
Dlimeng43 分钟前
在 Azure OpenAI 上利用 GPT-35-Turbo 和 GPT-4 开启 AI 创新之旅
人工智能·python·ai·语言模型·gpt-3·openai·azure
IT学长编程1 小时前
计算机毕业设计 基于Python的广东旅游数据分析系统的设计与实现 Python毕业设计 Python毕业设计选题 Spark 大数据【附源码+安装调试】
大数据·python·数据分析·毕业设计·毕业论文·计算机毕业设计选题·广东旅游数据分析系统
IT学长编程1 小时前
计算机毕业设计 内蒙古旅游景点数据分析系统的设计与实现 Python毕业设计 Python毕业设计选题 Spark 大数据【附源码+安装调试】
大数据·hadoop·python·数据分析·毕业设计·毕业论文·计算机毕业设计选题