請實現(xiàn)一個函數(shù),把字符串中的每個空格替換成"%20"秧饮。
解析:
從后往前替換映挂。首先計算出需要的容量,然后從最后一位開始從后往前填寫內(nèi)容盗尸。
答案:
//時間復(fù)雜度為 O(n)
//length為字符數(shù)組str的總?cè)萘扛檀笥诨虻扔谧址畇tr的實際長度
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--] = '%';
}
}
}