Python O(1) space O(n) time


  • 0
    V
    class Solution:
        # @param s, a list of 1 length strings, e.g., s = ['h','e','l','l','o']
        # @return nothing
        def reverseWords(self, s):
            self.reverseStr(s, 0, len(s) - 1)
        
            pos = 0
            while pos < len(s):
                wordEnd = pos
                while wordEnd < len(s) and s[wordEnd] != ' ':
                    wordEnd += 1
                
                rswap = wordEnd - 1
                self.reverseStr(s, pos, rswap)
                pos = wordEnd + 1
        
        def reverseStr(self, s, l, r):
            while l < r:
                tmp = s[l]
                s[l] = s[r]
                s[r] = tmp
                l += 1
                r -= 1
            
    

Log in to reply
 

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