剑指Offer(Python多种思路实现):替换空格

剑指Offer(Python多种思路实现):替换空格

面试5题:

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

解题思路一:剑指offer解法:①先计算源字符串数组长度,并统计空格数量②新字符串数组长度=源数组长度+2*空格数量③在新字符串数组上,从后向前遍历,通过两个index移动并复制。

class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # method 1:
        #return '%20'.join(s.split(' '))
        
        # method 2:
        #return s.replace(' ','%20')
        
        # method 3:
        #计算空格数量
        s=list(s)
        count=0
        for e in s:
            if e == ' ':
                count+=1
        p1=len(s)-1 # p1为原始字符串数组末尾的index
        #求新数组长度
        s+=[None]*(count*2)
        p2=len(s)-1 # p2为新字符串数组末尾的index
        while p1>=0:
            if s[p1]==' ':
                for i in ['0','2','%']:
                    s[p2]=i
                    p2-=1
            else:
                s[p2]=s[p1]
                p2-=1
            p1-=1
        return ''.join(s)

解题思路二:

def replaceSpace(self, s):
    return ''.join(c if c!=' ' else '%20' for c in s)

解题思路三:

class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return s.replace(' ','%20')
发布了18 篇原创文章 · 获赞 1 · 访问量 4210

猜你喜欢

转载自blog.csdn.net/weixin_44151089/article/details/104386986