剑指Offer3
替换空格
https://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&tqId=11155&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github
题目
思路
C++这里直接将数组长度标记乘2+原长度既可,不用再另外申请内存空间
Code
class Solution { public: void replaceSpace(char *str,int length) { //判空操作 if(str == nullptr || length < 0) return; int P1 = length - 1; int cnt = 0; for(int i = 0; i < length; i++) { if(str[i] == ' ') { cnt++; } } int P2 = length + cnt * 2 - 1; while(P1 < P2 && P1 >= 0) { if(str[P1] == ' ') { P1--; str[P2--] = '0'; str[P2--] = '2'; str[P2--] = '%'; } else if(str[P1] != ' ') { str[P2--] = str[P1]; P1--; //注意位置 } } } };