机试练习7.11

来源:互联网 发布:医药公司进销存软件 编辑:程序博客网 时间:2024/05/21 08:04

题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:没有什么比较好的办法,首先将字符串遍历一遍, 找出字符串中的空格数,从后往前再次遍历字符串,同时将字符后移,这样省空间。

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