Python reverse a whole list and then reverse each word divided by ' '


  • 0

    I personally feel it's clean. Only a pitfall is to handle in case i == len(s) - 1.

    class Solution:
        # @param s, a list of 1 length strings, e.g., s = ['h','e','l','l','o']
        # @return nothing
        def reverseWords(self, s):
            s = reverse(s, 0, len(s)-1)
            
            i, start = 0, 0
            while i < len(s):
                if s[i] == ' ':
                    s = reverse(s, start, i-1)
                    start = i + 1
                elif i == len(s)-1:
                    s = reverse(s, start, i)
                i += 1
            
        
    def reverse(s, i, j):
        while i < j:
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1
        return s
    

Log in to reply
 

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