剑指offer5-替换空格

剑指offer5-替换空格

    请实现一个函数,把字符串中的每个空格替换成"%20"。
    你可以假定输入字符串的长度最大是1000。
    注意输出字符串的长度可能大于1000。

样例

输入:"We are happy."
输出:"We%20are%20happy."

思路

    1、思路简单,看代码就懂,碰到空格就替换,python的话也可以直接用str.replace(" “, " %20”);
    2、若是用数组或者C语言,这一类,需要先遍历一遍数组,计算出有多少个空格,然后从固定的位置从后往前遍历数组,碰到空格的时候替换为“%20”。

AcWing-16 C++ code


class Solution {
public:
    string replaceSpaces(string &str) {
        string res = "";
        for(auto x : str){
            if(x == ' '){
                res += "%20";
            }else{
                res += x;
            }
        }
        return res;
    }
};

牛客网 C++ code :

class Solution {
public:
	void replaceSpace(char *str,int length) {
        int space_count = 0;
        for(int i = 0; i < length; i++){
            if(str[i] == ' '){
                space_count++;
            }
        }
        int right_index = space_count * 2 + length - 1;
        for(int i = length - 1; i >= 0; i--){
            if(str[i] == ' '){
                str[right_index--] = '0';
                str[right_index--] = '2';
                str[right_index--] = '%';
            }else{
                str[right_index--] = str[i];
            }
        }
	}
};

AcWing-16 python code

class Solution(object):
    def replaceSpaces(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = ""
        n = len(s)
        for i in range(n):
            if s[i] == ' ':
                res += "%20"
            else:
                res += s[i]
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值