剑指offer 面试题6 (从尾到头打印链表) python

题目描述

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

 

方法一:

# -*- coding:utf-8 -*-

class Solution:

    # s 源字符串

    def replaceSpace(self, s):

        # write code here

        s_new = s.split(" ")

        return ("%20").join(s_new)

思路:先用split把句子根据空格分开,然后再用“%20”拼接。

 

方法二:
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = s.replace(' ','%20')
        return s

 

 

方法三:

# -*- coding:utf-8 -*-

class Solution:

    # s 源字符串

    def replaceSpace(self, s):

        # write code here

        a = len(s)

        num =0

        if s:

            for i in range(a):

                if s[i]==" ":

                    num += 1

                index_2 = len(s) + 2 * num

                new_string = [None for i in range(index_2)]

                index_2-=1

            for i in range(a-1,-1,-1):

                if s[i]!=" ":

                    new_string[index_2] = s[i]

                    index_2-=1

                elif s[i]==" ":

                    new_string[index_2]="0"

                    new_string[index_2-1]="2"

                    new_string[index_2-2]="%"

                    index_2 -= 3

            return ("").join(new_string)

        else:

            return ""

 

剑指offer的思路:开辟一个数组来存放新的字符串,设置两个指针分别指向新旧字符串的首元素,遍历原字符串,碰到空格时,在新字符串上加入%20,否则等于原来的字符。

思路2:定义两个指针,P1指向原始字符串的尾部,P2指向替换后的字符串的末尾,向前移动指针P1,将碰到的字符复制到P2中,当碰到空格时,向P2逐渐中插入’0‘、‘2’、‘%'P1向前移一位。当碰到最后一个空格时,P1P2指向同一个位置,表明字符串都已经替换完毕。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值