8-剑指offer: 替换空格

题目描述

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

代码:

class Solution {
public:
	void replaceSpace(char *str,int length) {
        // 先统计需要替换的空格个数
        int cnt = 0;
        for (size_t index = 0; index < length; index++) {
            if (str[index] == ' ') {
                cnt++;
            }
        }
        
        // 替换后的字符串长度
        int new_length = length + 2*cnt;
        // 从右往左移动字符
        int index_new = new_length - 1, index_old = length-1;
        while(index_new>=0 && index_old>=0) {
            if (str[index_old] == ' ') {
                str[index_new--] = '0';
                str[index_new--] = '2';
                str[index_new--] = '%';
                index_old--;
            } else {
                str[index_new--] = str[index_old--];
            }
        }
	}
};

思路就是先遍历一遍,确定替换之后的字符串长度,然后再从右往左遍历字符串,按位移动,遇到空格,就连续插入三个字符.

posted @ 2019-05-21 19:12  星星,风,阳光  阅读(102)  评论(0编辑  收藏  举报