首页 > 其他 > 详细

8-剑指offer: 替换空格

时间:2019-05-21 19:25:11      阅读:127      评论:0      收藏:0      [点我收藏+]

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%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--];
            }
        }
    }
};

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

8-剑指offer: 替换空格

原文:https://www.cnblogs.com/xl2432/p/10901767.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!