[Python数据结构与算法] 2. 替换空格

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
时间限制:1秒 空间限制:32768K
online test

这,对python来说不是送分题吗。。。

class Solution:
    def replaceSpace(self, s):
        return s.replace(' ','%20')

time: 22ms
memory: 5720k

OK 尝试一下string的拼接

class Solution:
    def replaceSpace(self, s):
        str_ = ''    
        for char in s:
            str_ = str_ + '%20' if char == ' ' else str_ + char
        return str_

time: 21ms
memory: 5624k

参考

python string

你可能感兴趣的:([Python数据结构与算法] 2. 替换空格)