Simple python code using two states, which is easy to understand


  • 0
    A

    I scan the string from the right side, of course from the left side should be ok, too. In the current scanning position, the position only lies inside or outside of a word (inside 1, outside 0). When the state transfers from the outside to the inside, the inword variable is changed from 0 to 1, and the start and end of the word is also changed. When the state transfers from inside to outside, print the word or as in my code, store the word in the res string, then inWord is set to be 0

    class Solution:
        # @param s, a string
        # @return a string
        def reverseWords(self, s):
            if s is None:
                return
    
            wordLeft = 0
            wordRight = 0
            inWord = 0
    
            res =''
    
            for i in xrange(len(s)-1,-2,-1):
                if i <0:
                    if inWord == 1:
                        res += (s[wordLeft:wordRight]+ ' ')
                    break
    
                if inWord == 0:
                    if s[i] != ' ':
                        inWord = 1
                        wordRight = i+1
                        wordLeft = i
                elif inWord == 1:
                    if s[i] !=' ':
                        wordLeft -= 1
                    else:
                        res += (s[wordLeft:wordRight]+ ' ')
                        inWord = 0
    
    
            res = res[0:len(res)-1]
            return res

Log in to reply
 

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