class Solution {
public:
void replaceSpace(char *str,int length) {
//变量定义区
int newtv = 0;
int oldtv = 0;
int spaceNum = 0;
//入参有效性判断
if( NULL == str || length <= 0)
return;
//计算空格数目
int i =0;
while(str[i] != ‘\0‘)
{
oldtv++;
if(str[i] == ‘ ‘)
spaceNum++;
i++;
}
newtv = oldtv + 2*spaceNum;
if(newtv > length)
return;
//从后往前复制
while(newtv > oldtv)
{
while(str[oldtv] != ‘ ‘)
{
str[newtv--] = str[oldtv--];
}
oldtv--;
str[newtv--] = ‘0‘;
str[newtv--] = ‘2‘;
str[newtv--] = ‘%‘;
}
return;
}
};
程序已通过牛客网测试用例。
时间: 2024-10-14 17:30:04