【剑指offer】替换空格

来源:互联网 发布:android eventbus源码 编辑:程序博客网 时间:2024/06/07 18:48
时间限制:1秒 空间限制:32768K 热度指数:33643

本题知识点: 字符串

题目描述

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

思路:先计算出替换后的字符串长度,然后从后往前重写字符串。
class Solution {public:void replaceSpace(char *str,int length) {                int oldlength = strlen(str);                if(oldlength<0)            return;                      int spaceNum = 0;                for(int i=0;i<oldlength;i++)        {            if(str[i] == ' ')                spaceNum++;        }                if(spaceNum == 0)            return;                int newlength = 2*spaceNum + oldlength;                if(newlength>length)            return;                int p = newlength;        int q = oldlength;        while(q>=0)        {            if(str[q] == ' ')            {                str[p--] = '0';                str[p--] = '2';                str[p--] = '%';            }            else            {                str[p--] = str[q];            }                     q--;                     }                   }};


0 0
原创粉丝点击