剑指Offer刷题笔记——替换空格

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

主要思路:

1.用python字符串的replace方法。
2.对空格split得到list,用‘%20’连接(join)这个list。
3.由于替换空格后,字符串长度需要增大。先扫描空格个数,计算字符串应有的长度,从后向前一个个字符复制(需要两个指针)。这样避免了替换空格后,需要移动的操作。

遍历一次字符串,这样就可以统计出字符串空格的总数,并可以由此计算出替换之后的字符串的总长度。每替换一个空格,长度增加2,因此替换以后字符串的长度等于原来的长度加上2乘以空格数目。以"We are happy"为例,"We are happy"这个字符串的长度为14(包括结尾符号"\n"),里面有两个空格,因此替换之后字符串的长度是18。

 

# -*- 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:
            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)

另外也可以只在一个列表上操作,直接在原来的列表开辟出新的空间,用两个指针,一个字符串的末尾,另一个指向整个列表的末尾。

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        num_space = 0
        a = []
        for i in s:
            if i == ' ':
                num_space += 1
            a.append(i)
        new_length = len(s) + 2 * num_space
        for i in range(len(s),new_length):
            a.append(None)
        p1 = len(s)-1
        p2 = new_length-1
        while p1>=0:
            if a[p1]==' ':
                a[p2]='0'
                p2-=1
                a[p2]='2'
                p2-=1
                a[p2]='%'
                p2-=1
            else:
                a[p2] = a[p1]
                p2-=1
            p1-=1
        return ''.join(a)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值