剑指offer(python版)——2、替换空格

本文详细介绍了三种在Python中将字符串中的空格替换成'%20'的方法,包括使用replace函数的暴力解法,以及不使用内置函数的手动替换算法。通过实例代码展示了每种方法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

牛客网网址:(https://www.nowcoder.com/ta/coding-interviews)
leetcode网址:(https://leetcode-cn.com/problemset/lcof/)

思路

1、暴力解题——replace直接替换
2、从前向后记录‘ ’数目,从前向后替换‘ ’。
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        #方法一:暴力解题:replace函数替换
        #s= s.replace(' ','%20')
        #return s
    
        #方法二:
        '''
        ss = []
        for i in range(len(s)):
            if s[i] == ' ':
                ss.append('%20')
            else:
                ss.append(s[i])
        return ''.join(ss)
        '''
        #方法三:
        #插入法
        s_len = len(s)
        count = 0
        for i in s:
            if i ==' ':
                count+=1
        res = [' ']*(s_len+2*count)
        j = 0
        for i in range(s_len):
            if s[i] == ' ':
                res[j] = '%'
                res[j+1] = '2'
                res[j+2] = '0'
                j += 3
            else:
                res[j] = s[i]
                j+=1
        return ''.join(res)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值