剑指offer刷题记录之替换空格

1. 题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

2. 暴力替换

首先新建一个空字符串,然后遍历每个字符;
如果该字符不是空格,则添加该字符到新建字符串末端;
如果该字符是空格,则添加‘%20’到新建字符串末端。

class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        new_s = ''
        for i in s:
            if i == ' ':
                i = '%20'
            new_s = new_s + i
        return new_s

3. python内置函数

class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return s.replace(" ","%20")
发布了38 篇原创文章 · 获赞 98 · 访问量 36万+

猜你喜欢

转载自blog.csdn.net/xijuezhu8128/article/details/104676722