剑指Offer [Python] | 2 替换空格

「剑指Offer [Python] 」系列博文,主要是转载思路详细易懂的、python语言的优秀博文,加之整理和汇总各方资料,学习和对比多种思路(i.e. 暴力解法 vs 快速解法)。

❤️ 「更多题目」

《剑指Offer [Python] | 目录索引》

  • 题目

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

今天的题目可非常厉害了,大神一人贡献了3种解法,让我们快来看看吧?。

解法均摘自:https://www.cnblogs.com/yajun-yin/p/8596338.html

一、最简单的解法:用python的Replace函数
class Solution():
    def replaceSpace(self, s):
        return s.replace(' ','%20')
二、如果不能用Replace呢?用split?
  • 思路
    对空格split得到list,用‘%20’连接(join)这个list
class Solution():
    def replaceSpace(self, s):
        return '%20'.join(s.split(' '))
三、如果不能用自带的函数呢?从后向前边复制边替换?
  • 思路
    由于替换空格后,字符串长度需要增大。先扫描空格个数,计算字符串应有的长度,从后向前一个个字符复制(需要两个指针)。这样避免了替换空格后,需要移动的操作。

  • Python实现

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        num_space = 0
        for i in s:
            if i == ' ':
                num_space += 1

        new_length = len(s) + 2 * num_space
        index_origin = len(s) - 1
        index_new = new_length - 1
        new_string = [None for i in range(new_length)]

        while index_origin >= 0 & (index_new > index_origin):
            if s[index_origin] == ' ':
                new_string[index_new] = '0'
                index_new -= 1
                new_string[index_new] = '2'
                index_new -= 1
                new_string[index_new] = '%'
                index_new -= 1
            else:
                new_string[index_new] = s[index_origin]
                index_new -= 1
            index_origin -= 1
        return ''.join(new_string)


if __name__ == '__main__':
    a = Solution()
    print(a.replaceSpace('r y uu'))


来源:https://www.cnblogs.com/yajun-yin/p/8596338.html
  • 「个人remark ⚠️」

1. 关于代码

while index_origin >= 0 & (index_new > index_origin):

这个语句,充满了坑。到底是什么情况下,进入循环呢?

如果你理解成了 while ((index_origin >= 0) & (index_new > index_origin)):,那么这又是另外一个含义了,在本题中,就不能通过测试了。

?逻辑运算符 优先于 比较运算符

所以,

while index_origin >= 0 & (index_new > index_origin):
	 -> while index_origin >= (0 & (index_new > index_origin)):
    	-> while index_origin >= 0

因为,无论index_new > index_origin真假, (0 & (index_new > index_origin)) = 0

在这里插入图片描述
2. 哪怕第三种方法在这三种解法中,最为复杂。可是他有两点仍旧值得引起注意:

(1)他不依赖于内置函数,如果不能用函数,该怎么写?
(2)注意一个细节 —— 从后向前复制和替换。如果从前向后,每次还要移动后边的所有元素,将会更复杂。所以,从后向前是更聪明的方法。

不断比较,开阔思路,才会学到更多~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值