请实现一个函数,把字符串中的每个空格替换成"%20"。
解析:
从后往前替换。首先计算出需要的容量,然后从最后一位开始从后往前填写内容。
答案:
//时间复杂度为 O(n)
//length为字符数组str的总容量,大于或等于字符串str的实际长度
void ReplaceBlank(char str[], int length)
{
if (nullptr==str || length<=0) return;
int size = 0, blank_cnt = 0;
for (int i=0; i<=length && str[i]!='\0'; ++i)
{
++size;
if (str[i]==' ') ++blank_cnt;
}
int new_size = size + 2*blank_cnt;
if (new_size>length) return;
int ind_new=new_size-1, ind_old=size-1;
while (ind_new>=0 && ind_old>=0)
{
if (str[ind_old]!=' ')
str[ind_new--] = str[ind_old--];
else
{
--ind_old;
str[ind_new--] = '0';
str[ind_new--] = '2';
str[ind_new--] = '%';
}
}
}