剑指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指向同一个位置,表明字符串都已经替换完毕。

猜你喜欢

转载自blog.csdn.net/chocolate_chuqi/article/details/80812812
今日推荐