当前位置:网站首页>Reversing words in a string in LeetCode
Reversing words in a string in LeetCode
2022-08-10 12:57:00 【·The sea of stars】
题目
给你一个字符串 s ,颠倒字符串中 单词 的顺序.
单词 是由非空格字符组成的字符串.s 中使用至少一个空格将字符串中的 单词 分隔开.
返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串.
注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格.返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格.
示例 1:
输入:s = “the sky is blue”
输出:“blue is sky the”
示例 2:
输入:s = " hello world "
输出:“world hello”
解释:颠倒后的字符串中不能存在前导空格和尾随空格.
示例 3:
输入:s = “a good example”
输出:“example good a”
解释:如果两个单词间有多余的空格,颠倒后的字符串需要将单词间的空格减少到仅有一个.
提示:
1 <= s.length <= 10^4
s 包含英文大小写字母、数字和空格 ’ ’
s 中 至少存在一个 单词
进阶:如果字符串在你使用的编程语言中是一种可变数据类型,请尝试使用 O(1) 额外空间复杂度的 原地 解法.
来源:力扣(LeetCode)
解题思路
可以直接利用pythonfilters and character slices forjoin完成题目要求.
class Solution:
def reverseWords(self, s: str) -> str:
s=list(filter(lambda x:x!='',s.split(' ')))
s.reverse()
return ' '.join(s)
The advanced requirement of the topic is that it needs to be operated in place,We can simulate the function just now,Remove extra spaces from the string first,Then reverse the entire string,Finally iterate over the entire reversed string,Reverse one by one for a single word.
class Solution:
def reverseWords(self, s: str) -> str:
s=s.strip()
i,flag=0,1
while i<len(s):
while not flag and s[i]==' ':
s=s[0:i]+s[i+1:]
flag=1
if flag and s[i]==' ':
flag=0
i+=1
n=len(s)
def swap(a,b,s):
temp=s[a]
s=s[0:a]+s[b]+s[a+1:]
s=s[0:b]+temp+s[b+1:]
return s
for i in range(n//2):
s=swap(i,n-1-i,s)
temp,count='',0
s+=' '
for i in s:
if i!=' ':
temp=i+temp
else:
s=s[0:count-len(temp)]+temp+s[count:]
temp=''
count+=1
return s[:-1]
边栏推荐
猜你喜欢
随机推荐
Comparison version number of middle questions in LeetCode
Guo Jingjing's personal chess teaching, the good guy is a robot
阿里架构师整理一份企业级SSM架构实战文档,让你熟悉底层原理
在web页面播放rtsp流视频(webrtc)
毕业总结
LeetCode简单题之合并相似的物品
查看 CUDA cudnn 版本 & 测试 cuda 和 cudnn 有效性「建议收藏」
47Haproxy集群
娄底疾控中心实验室设计理念说明
[List merge] Combine multiple lists into one list
吃透Chisel语言.36.Chisel实战之以FIFO为例(一)——FIFO Buffer和Bubble FIFO的Chisel实现
Mysql—— 内连接、左连接、右连接以及全连接查询
Nanodlp v2.2/v3.0光固化电路板,机械开关/光电开关/接近开关的接法和系统状态电平设置
瑞幸「翻身」?恐言之尚早
Does face attendance choose face comparison 1:1 or face search 1:N?
A detailed explanation of implementation api embed
Proprietary cloud ABC Stack, the real strength!
Chapter 5 virtual memory
动态规划之最长回文子串
The god-level Alibaba "high concurrency" tutorial - basic + actual combat + source code + interview + architecture is all-inclusive