close

Question:

Similar to Question [6. Reverse Words in a String], but with the following constraints:

“The input string does not contain leading or trailing spaces and the words are always separated by a single space.”

Could you do it in-place without allocating extra space?


class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        a = list(s)
        left = 0
        right = len(a) - 1
        while left < right:
            tmp = a[left]
            a[left] = a[right]
            a[right] = tmp
            left += 1
            right -= 1
    
        left = 0
        right = left
        while right < len(a):
            if a[right] == ' ':
                ll = left
                rr = right - 1
                while ll < rr:
                    tmp = a[ll]
                    a[ll] = a[rr]
                    a[rr] = tmp
                    ll += 1
                    rr -= 1
                left = right + 1
            right += 1

        return ''.join(a)
 


 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 g0d2 的頭像
    g0d2

    kazi1@的部落格

    g0d2 發表在 痞客邦 留言(0) 人氣()