「LeetCode每日一题」—— 151. 翻转字符串里的单词
151. 翻转字符串里的单词
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string/
难度:中等
题目
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
思路
内置函数调用:
使用 split 将字符串按空格分割成字符串数组;
使用 reverse 将字符串数组进行反转;
使用 join 方法将字符串数组拼成一个字符串。


当然你也可以自己写,代码见解决方案。
方案代码
解决方案:
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split()))
相关
原创文章,作者:flypython,如若转载,请注明出处:http://flypython.com/algorithm/leetcode/319.html
相关推荐
-
「LeetCode每日一题」—— 42. 接雨水
42. 接雨水 链接:https://leetcode-cn.com/problems/trapping-rain-water/难度:困难 题目 给定 n 个非负整数表示…
04/04/2020 -
「LeetCode每日一题」—— 542. 01 矩阵
542. 01 矩阵 链接:https://leetcode-cn.com/problems/01-matrix/难度:中等 题目 点击原文链接跳转查看题目 思路 这道题求的就是每…
15/04/2020 -
「LeetCode每日一题」——1160. 拼写单词
1160. 拼写单词 链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters…
17/03/2020 -
「LeetCode每日一题」——876. 链表的中间结点
876. 链表的中间结点 链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/难度:简单 题目 给定一个带有…
23/03/2020 -
「LeetCode每日一题」——169. 多数元素
169. 多数元素 链接:https://leetcode-cn.com/problems/majority-element/难度:简单 题目 给定一个大小为 n 的数组,找到其中…
13/03/2020 -
「LeetCode每日一题」——695. 岛屿的最大面积
695. 岛屿的最大面积 链接:https://leetcode-cn.com/problems/max-area-of-island/难度:中等 题目 给定一个包含了一些 0 和…
15/03/2020 -
「LeetCode每日一题」206. 反转链表
206. 反转链表 题目 反转一个单链表。 示例: 输入: 1->2->3->4->5->NULL输出: 5->4->3->2-&g…
02/03/2020 -
「LeetCode每日一题」——LCOF.57 – II. 和为s的连续正数序列
面试题57 – II. 和为s的连续正数序列 链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu…
06/03/2020 -
「LeetCode每日一题」—— 56. 合并区间
56. 合并区间 链接:https://leetcode-cn.com/problems/merge-intervals/难度:中等 题目 给出一个区间的集合,请合并所有重叠的区间…
16/04/2020 -
「LeetCode每日一题」—— 466. 统计重复个数
466. 统计重复个数 链接:https://leetcode-cn.com/problems/count-the-repetitions/难度:困难 题目 思路 这是一道困难题,…
19/04/2020
您必须登录才能发表评论。