牛客--2 替换空格

题目描述:

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

注意:题目中的“ ”替换成长度为3的字符串,所以数组长度增加了。

python解决方法:先把字符串转化成列表,进行替换,然后把列表转化回字符串

lis = list(s)
leng = len(s)
for i in range(0,leng):
    if i == '':
        lis[i] = '%20'
return ''.join(lis)
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        if s is None or s == "":
            return ''
        sl = list(s)
        l = len(s)
        num = 0
        for i in sl:
            if i == ' ':
                num+=1
        ll = l + num*2
        p1 = l-1
        p2 = ll-1
        sl = sl + [0]*num*2
        while p1>=0:
            if sl[p1] == ' ':
                sl[p2] = "0"
                sl[p2-1] = "2"
                sl[p2-2] = '%'
                p2 = p2-3
                p1-=1
            else:
                sl[p2] = sl[p1]
                p1-=1
                p2-=1
        return ''.join(sl)

php

<?php
function replaceSpace($str)
{
    // wri   te code here
    $r = str_replace(" ","%20",$str);
    return $r;
}

猜你喜欢

转载自blog.csdn.net/yl_mouse/article/details/82106979