[剑指offer]面试题4(替换空格)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hua12134/article/details/79149784

题目:请实现一个函数,把字符串中的每个空格替成“%20”。例如输入“we are happy.”,则输出“we%20are%20happy.”。

基本思路:先遍历一遍字符串统计字符串中空格的个数并计算出替换之后的字符串的总长度,每替换一个空格,长度增加2,因此替换后字符串的长度对于原来的长度加上空格个数的2倍。如果从头到尾扫描字符串,遇到空格就做替换,必须每次都把空格后面所有的字符都向后移动两个字节,这样处理的时间复杂度为O(n²),效率比较低。我们还有更好的方法,
从字符串的后面开始复制(没遇到空格)和替换(遇到空格),这样所有的字符都只复制(移动)一次,时间复杂度为O(n)。提高了效率

#include <iostream>

using namespace std;

void ReplaceBlank(char str[], int length)
{
    if (NULL == str && length <= 0)
        return;

    int oldLength = 0;      //字符串实际长度
    int num = 0;            //空格个数
    int i = 0;

    while(str[i] != '\0')
    {
        oldLength++;
        if (str[i] == ' ')
            num++;

        i++;
    }
    int newLength = oldLength + num * 2;
    if (newLength > length)
        return;

    int tmp1 = oldLength;
    int tmp2 = newLength;
    while(tmp1 >= 0 && tmp2 > tmp1)
    {
        if (str[tmp1] == ' ')
        {
            str[tmp2--] = '0';
            str[tmp2--] = '2';
            str[tmp2--] = '%';
        }
        else
        {
            str[tmp2--] = str[tmp1];
        }
        tmp1--;
    }
}

int main()
{
    char str[100] = "We are happy";
    int length = sizeof(str);
    ReplaceBlank(str, length);
    printf("%s\n", str);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/hua12134/article/details/79149784