题目描述:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

Solutions

  两次反转字符串,第一次反转整句,第二次反转每个单词。

# -*- coding:utf-8 -*-
class Solution:
    def ReverseString(self, s):
        if s is None:
            return None
        begin = 0
        end = len(s) - 1 
        while begin < end:
            s[begin], s[end] = s[end], s[begin]
            begin += 1
            end -= 1
        return s

    def ReverseSentence(self, s):
        # write code here
        if s is None:
            return None
        s = list(s)
        s = self.ReverseString(s)
        begin = end = 0
        n = len(s)
        while begin < n:
            if s[begin] == ' ':
                begin += 1
                end += 1
            elif end < n and s[end] == ' ':
                s[begin:end] = self.ReverseString(s[begin:end])
                begin = end
            elif end < n:
                end += 1
            elif end == n:
                s[begin:end] = self.ReverseString(s[begin:end])
                break
        return ''.join(s)

References

  1. 042a. 翻转单词序列