题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
添加链接描述
Python 代码实现
python自带函数
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
if len(s) <=0:return s
return ' '.join(s.split(' ')[::-1])
字符串技巧
Python
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
if len(s) <=0: return s
s =list(s)
s.append(' ')
start,end,length = 0,0,len(s)
for i in range(length):
if s[i] == ' ':
end = i-1
while end>start:
s[end],s[start] = s[start],s[end]
start +=1
end -= 1
start = i+1
for i in range(length>>1):
s[i],s[length-1-i] = s[length-1-i],s[i]
return ''.join(s)[1:]