Python O(1) Solution with Two Pointer


  • 0
    W
    class Solution(object):
        def reverseWords(self, s):
            """
            :type s: str
            :rtype: str
            """
            start, end = len(s) - 1, len(s) - 1
            res = ""
            while start >= 0:
                if s[start] == " " and s[end] == " ":
                    start -= 1
                    end -= 1
                elif s[start] == " ":
                    res += s[start + 1: end + 1] + " "
                    end = start
                else:
                    start -= 1
            if start < end:
                res += s[: end + 1]
            else:
                res = res[:-1]
            return res
                    
    

Log in to reply
 

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