剑指offer-替换空格

题目地址:https://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&&tqId=11155&rp=1&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking

双指针,多申请2*空格数的内存。从后往前遍历

 1 class Solution {
 2 public:
 3     void replaceSpace(char *str,int length) {
 4         //从后往前遍历
 5         int spaceNum=0;//空格数量
 6         for(int i=0;i<length;++i){
 7             if(str[i]==' ')spaceNum++;
 8         }
 9         str=(char *)realloc(str,(length+2*spaceNum)*sizeof(char));//多申请2*spaceNum的空间
10         for(int i=length-1,j=length+2*spaceNum-1;i>=0;--i){
11             if(str[i]!=' '){
12                str[j--]=str[i]; 
13             }else{
14                 str[j--]='0';
15                 str[j--]='2';
16                 str[j--]='%';
17             }
18         }
19     }
20 };

 

posted @ 2020-09-17 11:08  LifeRunningError  Views(104)  Comments(0Edit  收藏  举报