剑指 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))