【剑指Offer笔记】:替换空格

2019-04-05  本文已影响0人  w8ed

题目描述

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

思路

因为替换空格会覆盖后面字符,因此我们填充顺序为从后往前放。总最后一位开始,每放一个字符,指针就往前移动一个字符,从而使得:后面的都是处理好的部分,前面是待处理的部分。直接插入排序也用到了这个思路。

include <iostream>

using namespace std;

class Solution
{
public:
void replaceSpace(char *str, int length)
{
int lenSrc = length - 1;

    int count = 0;
    for (int i = 0; i < lenSrc; i++)
    {
        if (str[i] == ' ')
        {
            count++;
        }
    }

    int lenDst = lenSrc + count * 2; //每个空格占1位,%20占3位,比原来多2位

    int i = lenSrc;
    int j = lenDst;

    while (i >= 0)
    {
        if (str[i] != ' ')
        {
            str[j] = str[i];
            j--;
        }
        else
        {
            str[j] = '0';
            j--;
            str[j] = '2';
            j--;
            str[j] = '%';
            j--;
        }
        i--;
    }
    // str[lenDst] = '0';
}

};

int main()
{
char str[100] = "a b c";

Solution solu;
solu.replaceSpace(str, 5);

cout << str << endl;
cout << system("pause");
return 0;

}

牛客网在线检验:替换空格_牛客网


参考资料:https://blog.csdn.net/gatieme/article/details/51100630

上一篇 下一篇

猜你喜欢

热点阅读