题目描述:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
方法一:按空格分割字符串,反向连接建立新字符串
def reversesentence(s):
words = s.split(' ')
newstr = ''
i = len(words)-1
while i > 0:
newstr += words[i]
newstr += ' '
i -= 1
newstr += words[0]
return newstr
方法二:遍历字符串,遇到空格入栈,遇到字符,获取整个单词再入栈,反向输出
def reversesentence(s):
list = []
i = 0
word = ''
restr = ''
while i < len(s):
if s[i] == ' ':
list.append(' ')
i += 1
else:
while i < len(s) and s[i] != ' ':
word += s[i]
i += 1
list.append(word)
word = ''
j = len(list)-1
while j >= 0:
restr += list[j]
j -= 1
return restr
方法三:翻转两次,第一次全部反转,第二次遇到单词翻转,遇到空格跳过