剑指offer4:字符串空格替换

我的做法:报错了不知哪里错了

class Solution {
public:
    string replaceSpace(string s) {
        int SpaceNum=0;
        int i=0;
        while(s[i]!='\0')
        {
            if(s[i]==' ')
                SpaceNum++;
           //空格长度
            i++;
        }
        int SecLen=i+SpaceNum*2;
        int indexSecond=SecLen,indexFir=i;
        for(;indexFir>=0;indexFir--)
           //对原来的s进行循环,然后再找空格
        {
            if(s[indexFir]!=' ')
            {
                s[indexSecond]=s[indexFir];
                indexSecond--;
            }
            else
            {
                s[indexSecond]='0';
                indexSecond--;
                s[indexSecond]='2';
                indexSecond--;
                s[indexSecond]='%';
                indexSecond--;
            }
        }
        return s;
    }
};
  1. 从后往前遍历数组,并且不需要开辟新的空间,而是直接在原数组上修改
class Solution {
public:
    string replaceSpace(string s) {
        if(s.empty()) return s;
        int spaceCount = 0, i = s.size() - 1;
        for(char c : s)
        {
            if(c == ' ') spaceCount ++;
        }
        // 扩容
        s.resize(s.size() + spaceCount * 2);
        int j = s.size() - 1;
        while(i != j)
        {
            // 从后往前替换空格
            if(s[i] != ' ')
            {
                s[j] = s[i];
                i--;
                j--;
            }
            else
            {
                i--;
                s[j] = '0';
                s[j-1] = '2';
                s[j-2] = '%';
                j -= 3;
            }
        }
        return s;
    }
};


  1. 字符串的修改在后面+=就可以了
class Solution {
public:
    string replaceSpace(string s) {
        string res;
        for(auto c : s){
            if(c == ' ')
                res += "%20";
            else
                res += c;
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值