天天刷leetcode——剑指 Offer 05. 替换空格

题目:offer 05. 替换空格

题目描述

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。[1]

解题思路

1. 遍历字符串,找到空格,使用replace替换

    def replaceSpace(self, s: str) -> str:
        for i in range(len(s)):
            if s[i] == " ":
                s = s.replace(s[i], '%20')
        return s

replace函数并不改变原来的字符串,而是返回来一个新的字符串。
有点投机取巧哈,使用replace函数。
在这里插入图片描述

2. 变成列表,遍历替换之后,使用join拼接

def replaceSpace(self, s: str) -> str:
        l = list(s)
        for i in range(len(l)):
            if l[i] == ' ':
                l[i] = '%20'
        return ''.join(l)

在这里插入图片描述

references

[1] https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

猜你喜欢

转载自blog.csdn.net/qq_30516823/article/details/107360245
今日推荐