Python 2 pointer solution


  • 0
    A
    class Solution(object):
        def reverseWords(self, s):
            listS = list(s) + [' '] #to account for corner case at the end
            
            i = 0
            for j in range(1, len(listS)):
                if listS[j] == ' ' and listS[j-1] != ' ':
                    listS[i:j] = reversed(listS[i:j])
                    i = j
                elif listS[j] != ' ' and listS[j-1] == ' ':
                    i = j
            
            return ''.join(listS[:-1])
    

Log in to reply
 

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