The title

Implement a function that replaces each space in the string s with “%20”. It’s an easy question.

Train of thought

First, it’s natural to think of replacing “%20” with “replace”.

return s.replace(" ","%20")

If you do not modify the original string, you can also create a new string, add a “%20” to the space and iterate backwards

Finally, use slices to modify the original string

code

class Solution:
    def replaceSpace(self, s: str) - >str:
        if not s:
            return ""
            
        l = len(s)
        p = 0
        while p<l:
            if s[p] == ' ':
                l+=2
                s = s[:p]+'% 20'+s[p+1:]
                p+=2
            else:
                p+=1
        return s
Copy the code