空格替换


2.

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

#!/usr/bin/python 2.7
# @author liuzhiqiang
# @date 2018-08
# @email [email protected]

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        length = len(s)
        space_count = 0
        for i in s:
            if i == ' ':
                space_count += 1
        new_len = length + space_count * 2
        res = list(s +  ' ' * (space_count * 2))
        p1 = length-1
        p2 = new_len-1
        while p1 >= 0 and p2 >= p1:
            if s[p1] == ' ':
                res[p2] = '0'
                p2 -= 1
                res[p2] = '2'
                p2 -= 1
                res[p2] = '%'
                p2 -= 1
            else:
                res[p2] = s[p1]
                p2 -= 1
                p1 -= 1
        return ''.join(res)
        

该类问题也就是replace的实现,只要保证从后往前修改就行

你可能感兴趣的:(空格替换)