Python solution without any built-in tricks


  • 0

    Seen too many python solutions using split() and [::-1] which are not supposed to use.

    class Solution(object):
        def reverseWords(self, s):
            sList = list(s + " ")
            start, end = 0, len(sList) - 1
            wstart, wend, preSpace, i = start, 0, True, start
            while i <= end:
                if sList[i] == ' ':
                    if preSpace:
                        sList.pop(i)
                        end -= 1
                        continue
                    wend = i - 1
                    self.reverseWord(sList, wstart, wend)
                    wstart = i + 1
                    preSpace = True
                else:
                    preSpace = False
                i += 1
            self.reverseWord(sList, start, end - 1)
            return "".join(sList[start:end])
    
        def reverseWord(self, sList, wstart, wend):
            for i in xrange(wstart, wstart + (wend + 1 - wstart)/2):
                sList[i], sList[wend + wstart - i] = sList[wend + wstart - i], sList[i]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.