JZ 05 & JZ 58


Solution to JZ 05 and JZ 58 II.

JZ 05

(Easy) [link]

class Solution:
    def replaceSpace(self, s: str) -> str:
        cnt = s.count(' ')
        res = list(s)
        res.extend([' '] * cnt * 2)
        left, right = len(s)-1, len(res)-1

        while left >= 0:
            if res[left] != ' ':
                res[right] = res[left]
                right -= 1
            else:
                res[right-2: right+1] = '%20'
                right -= 3
            left -= 1
        
        return ''.join(res)

JZ 58

(Easy) [link]

class Solution:
    def reverseLeftWords(self, s: str, n: int) -> str:
        s = list(s)
        s[:n] = list(reversed(s[:n]))
        s[n:] = list(reversed(s[n:]))
        s.reverse()
        return ''.join(s)
class Solution:
    def reverseLeftWords(self, s: str, n: int) -> str:
        def reverse_fn(s, left, right):
            while left < right:
                s[left], s[right] = s[right], s[left]
                left += 1
                right -= 1
                
        s = list(s)
        end = len(s)-1
        reverse_fn(s, 0, n-1)
        reverse_fn(s, n, end)
        reverse_fn(s, 0, end)
        return ''.join(s)

  TOC