题目:将“student. a am I”准变为“I am a student.”
方法1、从后向前遍历,用append加入结果列表的末尾
class Solution:
def reverse_word(self,s):
t=len(s)
res=[]
for i in range(len(s)-1,-1,-1): #生成逆向索引
if s[i]=' ':
res.append(s[i+1:t])
t=i
if i==0:
res.append(s[i:t])
return(''.join(res))
方法2、insert(index,新插入的元素)
class Solution:
def reverse_word(self,s):
t=0
res=[]
for i in range(len(s)):
if s[i]=' ':
res.inser(0,s[t:i])
t=i
if i==len(s)-1:
res.append(s[t:i+1])
return(''.join(res))
方法3、按空格将字符串分成多个单词,然后对列表逆序拼接成字符串
class Solution:
def reverse_word(self,s):
l=res.split()[::-1]
return(''.join(l))
``