双指针,多申请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 };