【剑指Offer】面试题5 替换空格

题目:在这里插入图片描述
代码:
c++ STL 方法 时间复杂度高

class Solution {
public:
    string replaceSpace(string s) {
        int pos = s.find(' ');
        while(pos != -1)
        {
            s.erase(pos,1);
            s.insert(pos,"%20");
            pos = s.find(' ');
        }
        return s;   
    }
};

代码片段2:

class Solution {
public:
    string replaceSpace(string s) {
        int Oldlength = s.size();
        int num = 0;
        int i = 0;
        while(s[i] != '\0')
        {
            if (s[i] == ' ')
                num ++;
            i++;
        }
        int Newlength = Oldlength + 2*num;
        s.resize(Newlength);

        int Oldindex = Oldlength;
        int Newindex = Newlength;
        while(Oldindex >= 0 && Oldindex < Newindex)
        {
            if(s[Oldindex] == ' ')
            {
                s[Newindex--] = '0';
                s[Newindex--] = '2';
                s[Newindex--] = '%';
            }
            else
            {
                s[Newindex--] = s[Oldindex];
            }
            Oldindex--;
        }
        return s;

        
    }
};

思想:从前往后填写,在字符串移动过程中 部分子串涉及多次移动,时间复杂度为O(n),而从后往前不存在此问题 为O(n)。

代码片段3:

class Solution {
public:
    string replaceSpace(string s) {     //字符数组
        string array;   //存储结果
        
        for(auto &c : s){   //遍历原字符串
            if(c == ' '){
                array += "%20";
            }
            else{
                array += c;
            }
        }
        return array;
    }
};

附加题:
有两个排序的数组a b ,实现b中的数字插入a中,并有序。
从头到尾比较易出现移动多次情况,而从后往前比较则无这个问题:
代码:

int main()
{
    int a[10] = {0,1,2,3,4};
    int b[5] = {0,1,4,6,7};
    int indexa = 4;
    int index = 9;
    int indexb = 4;
    while (indexa >= 0 && indexb >= 0)
    {
        if(a[indexa] >= b[indexb])
        {
            a[index--] = a[indexa];
            indexa--;
        }
        else
        {
             a[index--] = b[indexb];
             indexb--;
        } 
    }
    for(int i = 0; i < 10; i++)
    {
        cout << a[i];
    }
    cout << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值