题目
思路
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--; //注意位置
}
}
}
}; 
京公网安备 11010502036488号