44.翻转单词顺序列
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
记录
方法一:
拆分字符串,反向重组。
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
if s is None:
return s
l = s.split(" ")
return(" ".join(l[::-1]))
方法二:
栈。
全部入栈后依次出栈,并在每个元素之间添加‘ ‘。
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
if s is None or len(s) == 0:
return s
stack = s.split(' ')
res = ""
while len(stack) > 0:
res += stack.pop() + " "
res = res[:-1]
return res
方法三:
“student. a am I”
第一步:句子整体翻转 “I ma a .tneduts”
第二步:各个单词翻转 “I am a student.”
class Solution:
def ReverseSentence(self, s):
# write code here
if not s: return s
s = list(s)
#第一次:整体翻转
self.reverse(s, 0, len(s) - 1)
start, end = 0, 0
#第二次:各个单词翻转
while start < len(s):
if s[start] == ' ':
start += 1
end += 1
elif end == len(s) or s[end] == ' ':
self.reverse(s, start, end - 1)
end += 1
start = end
else:
end += 1
return ''.join(s)
def reverse(self, s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1