剑指offer(2) 字符串的替换

来源:互联网 发布:android获取xml数据 编辑:程序博客网 时间:2024/05/21 10:40

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

我们先观察我们的功能函数,void replaceSpace(char *str, int length);
这个函数中,没有返回值,就意味着我们的一级指针既是输入,也是输出。
然而,我们的数据肯定是str所指向的内存,一级指针做参数时,我们无法修改 (实参) 地址,让它指向其他的内存。
所以,我们必须要在str所指向的字符串上进行拷贝工作。
我们的字符串类似 “we are happy” 目标字符串“we%20are%20happy”
如果我们从前往后拷贝,那么就会修改到原来的数据而无法进行完整的空格与“%20”的替换。
那么我们只能由后往前。
解决方案:
1. 统计空格的个数
2. 计算由后往前的开始位置 字符串长度 + 空格个数 * (替换字符串-原字符串)
3. 由后往前挨个填写对应的数据

class Solution {public:    int countSpace(char * str, int length){        int count = 0;        for (int i = 0; i < length; i++)        {            if (str[i] == ' ')            {                count++;            }        }        return count;    }    void replaceSpace(char *str, int length) {        int count = 0;        count = countSpace(str, length);        int index = length + count*2-1;        for (int i = length-1; i >=0 ; i--)        {            if (str[i] != ' ')            {                str[index--] = str[i];            }            else{                str[index--] = '0';                str[index--] = '2';                str[index--] = '%';            }        }    }};
0 0
原创粉丝点击