牛客网-C++剑指offer-第二题(替换空格)

题目描述

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

 

解答:这题比较常规,没什么技术含量

答案:

class Solution {
public:
    void replaceSpace(char *str,int length) {

        for(int i = 0; i < length; ++i)
        {
            if(str[i] == ' ')
            {
                for (int j = length+1; j > i+2; --j) {
                    str[j] = str[j-2];
                }
                str[i] = '%';
                str[i+1] = '2';
                str[i+2] = '0';
            }
        }
    }
};

 

优化思路(直接调用函数):

class Solution {
public:
    void replaceSpace(char *str,int length) {

        string my_str = str;

        if (my_str.empty())
            return;

        while (my_str.find(" ") != string::npos)
        {
            my_str.replace(my_str.find(" "),1,"%20");

        }
        //这样cpy是不行的
        //char *newchar = new char(my_str.size());
        //strcpy(newchar,my_str.c_str());

        char nchar[my_str.size()];
        strcpy(nchar,my_str.c_str());
        str = nchar;    //不知道为什么传不出去

        cout<<str<<endl;

    }
};

int main()
{
    Solution solution;
    char *str = "We Are Happy";

    solution.replaceSpace(str,12);
    cout<<str<<endl;

    return 0;
}

 

优化思路(从后往前复制)

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <unordered_map>
#include <cstring>
#include <map>

using namespace std;

class Solution {
public:
    void replaceSpace(char *str,int length) {

        int count = 0;
        int i = 0;
        int origin_len = 0;
        while (str[i] != '\0')
        {
            origin_len++;
            if (str[i] == ' ')
                count++;
            i++;
        }

        int p1,p2;
        p1 = origin_len;
        p2 = p1 + count*2;

        if (p2 > length)
            return;

//        cout<<"p1:"<<p1<<" p2:"<<p2<<endl;
        for (int j = 0; j < origin_len + 1; ++j) {
            if (str[p1] == ' ')
            {
                str[p2--] = '0';
                str[p2--] = '2';
                str[p2--] = '%';
            } else{
                str[p2--] = str[p1];
            }
            p1--;
        }
        //string m_str = str;

    }
};

int main()
{
    Solution solution;
    //如果这样传参数会发生段错误
    //char * my_str = "We Are Happy.";
    char my_str[100] = "We Are Happy.";

    solution.replaceSpace(my_str,100);
    cout<<*my_str<<endl;

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值