当前位置:网站首页>剑指 Offer 58 - I. 翻转单词顺序,strip()函数
剑指 Offer 58 - I. 翻转单词顺序,strip()函数
2022-07-20 19:51:00 【愈努力俞幸运】
剑指 Offer 58 - I. 翻转单词顺序https://leetcode.cn/problems/fan-zhuan-dan-ci-shun-xu-lcof/
strip()函数,可以删除字符串首尾的所有空格
设立两个指针,界定要加入的字符。
'''
s='1 '
for i in range(len(s)):
if s[i-1]!=' ':#i==0时,i-1不存在,默认这个语句为真
print(i,'*')
ans=[]
ans.append(s[2:1])默认加入一个空字符串''
'''
'''
class Solution:
def reverseWords(self, s):
ans=[]
for i in range(len(s)):
if s[i]!=' ':
j=i
break
for i in range(len(s)):
if s[i]==' ' and s[i-1]!=' ':
if j<=i:
ans.append(s[j:i])
j=i+1
continue
if s[i]==' ' and s[i-1]== ' ':
j=i+1
continue
if (i == len(s) - 1 and s[i - 1] != ' ') or (i == len(s) - 1 and i==j):
ans.append(s[j:i+1])
res=[]
for i in range(len(ans)-1,-1,-1):
res.append(ans[i])
return ' '.join(res)
'''
class Solution:
def reverseWords(self, s):
s=s.strip()#删除字符串首尾的所有空格
i=j=len(s)-1
res=[]
while i>=0:
while i>=0 and s[i]!=' ':
i-=1
res.append(s[i+1:j+1])
while s[i]==' ':
i-=1
j=i
return ' '.join(res)
a=Solution()
s1="the sky is blue"
s2=" hello world! "
s3="a good example"
s4=' 1'
s5="1 "
print(a.reverseWords(s1))
print(a.reverseWords(s2))
print(a.reverseWords(s3))
print(a.reverseWords(s4))
print(a.reverseWords(s5))
边栏推荐
猜你喜欢
S2b2c mall system platform function module analysis, accelerate the implementation of digital transformation of pharmaceutical manufacturing enterprises
王者荣耀商城异地多活架构
【三维目标检测】Pointpillars(一)
单元测试,写起来到底有多痛?你会了吗
How to solve the problem that win11 printer document is suspended?
win11微软账户登录一直转圈怎么解决?win11微软账户登录一直转圈
S2B2C商城系统平台功能模块分析,加速医药制造企业数字化转型落地
2022年7月俄罗斯数据库排行榜:ClickHouse雄踞榜首,GigaBASE摘得榜眼
The simplest implementation of throttling and anti chattering
【三维目标检测】Pointpillars(二)
随机推荐
Simple opengauss SQL tuning using plan hint
百度经典面试题——判定素数(如何优化?)
简易学生管理系统项目:(增、删、查、改、模糊查、分页查、上传、下载、视频导入、当前系统时间) --- 《附源码》
STL 笔记(十二):关联性容器——集合
STL notes (XI): container adapter - priority queue
剑指 Offer 15. 二进制中1的个数
基于B\S架构搭建属于自己的股票分析系统
The simplest implementation of throttling and anti chattering
High score technical document sharing of ink Sky Wheel - Database Security (48 in total)
APR学习失败问题定位排查
Today's test told me that the merged data is invalid after data synchronization
Redis implements distributed current limiting (learning notes
物美与价廉,名创优品能否兼得?
什么?多商户系统不适配 APP?这不就来了么!
VS2005利用pdb加源码定位崩溃所在代码行
Is it safe for Orient Fortune Securities to open an account? What is the lowest commission?
findContours
容器网络:来去自由的日子,不买公寓去合租
小镇做题家的DBA之路
Commercial supply chain management system of big health industry: standardize procurement management and improve enterprise procurement efficiency