美文网首页
[Python数据结构与算法] 2. 替换空格

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

作者: revlis | 来源:发表于2018-07-20 21:52 被阅读0次

    请实现一个函数,将一个字符串中的每个空格替换成“%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. 替换空格

          本文链接:https://www.haomeiwen.com/subject/ynfcmftx.html