剑指offer 面试5题

面试5题:

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

方法一:

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return '%20'.join(s.split(' '))

方法二:

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return s.replace(' ','%20')

 

方法三:

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

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

 

posted @ 2018-06-12 11:00  Fintech带你飞  阅读(1912)  评论(0编辑  收藏  举报