Clean python solution with explanation


  • 0
    P

    class Solution(object):

    def reverseWords(self, s):
        ret=""
        while s:
            ### first ignore leading spaces
            i=0
            while i<len(s) and s[i]==' ':
                i+=1
            if i==len(s): break
            ### update string
            s=s[i:]
            ### then get the word and save it
            j=0
            while j<len(s) and s[j]!=' ':
                j+=1
            ret=s[:j]+' '+ret
            ### update again
            s=s[j:]
            
        return ret[:-1]

Log in to reply
 

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