当前位置:网站首页>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]
边栏推荐
- 【jstack、jps命令使用】排查死锁
- 【黑马早报】雷军称低谷期曾想转行开酒吧;拜登正式签署芯片法案;软银二季度巨亏230亿美元;北京市消协约谈每日优鲜...
- bat脚本——提取多个文件夹到指定路径
- [List merge] Combine multiple lists into one list
- 海外邮件发送指南(二)
- 数字藏品,“赌”字当头
- How to cultivate the design thinking of ui designers?
- phpstrom 快速注释:
- Data Analysis of Time Series (5): Simple Prediction Method
- 虚拟机桥接模式不能上网
猜你喜欢
培训机构学习费用是多少呢?
Guo Jingjing's personal chess teaching, the good guy is a robot
CURRENT_TIMESTAMP(6) 函数是否存在问题?
第5章 虚拟存储器
瑞幸「翻身」?恐言之尚早
中科院深圳先进技术院合成所赵国屏院士组2022年招聘启事
Behind IDC's No. 1 position, what kind of "video cloud" is Alibaba Cloud building?
跨域的五种解决方案
线代 | 秒杀方法与技巧
How to do foreign media publicity to grasp the key points
随机推荐
燃炸!字节跳动成功上岸,只因刷爆LeetCode算法面试题
百度用户产品流批一体的实时数仓实践
如何培养ui设计师的设计思维?
Guo Jingjing's personal chess teaching, the good guy is a robot
Data Analysis of Time Series (5): Simple Prediction Method
Deploy the project halfway through the follow-up
【mysql索引实现原理】
Prada, big show?In the yuan in the universe that!
Dining (web stream)
Excel function formulas - LOOKUP function
ASP.NET Core依赖注入系统学习教程:ServiceDescriptor(服务注册描述类型)
Hackbar 使用教程
LeetCode中等题之比较版本号
LeetCode简单题之合并相似的物品
啥?他一个人写了个价值100万的软件,却用来开源了!
Codeforces Round #276 (Div. 1) D. Kindergarten
基础 | batchnorm原理及代码详解
[List merge] Combine multiple lists into one list
48 the mysql database
Codeforces Round #276 (Div. 1) B. Maximum Value