翻转单词顺序列
翻转单词顺序列_牛客网
https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tqId=11197&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路1:先根据空格划分存到list中,再对list反转
def ReverseSentence(self, s): # write code here if not s: return "" l = [] j = 0 n = len(s) #l=s.split(' ') for i in range(n): if s[i] == ' ': l.append(s[j:i]) j = i + 1 l.append(s[j:]) begin = 0 end = len(l) - 1 while begin <= end: l[begin], l[end] = l[end], l[begin] begin += 1 end -= 1 return ' '.join(l)
思路2:先整体反转,再根据空格切分局部反转
def Reverse(self, s, begin, end): if not s: return None 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 not s: return "" revS = self.Reverse(list(s), 0, len(s) - 1) begin = 0 end = 0 while begin <= len(s) - 1: if revS[begin] == ' ': begin += 1 end += 1 elif revS[end] == ' ': self.Reverse(revS, begin, end-1) end += 1 begin = end elif end == len(s)-1: self.Reverse(revS, begin, end) end += 1 begin = end else: end += 1 return "".join(revS)