1.題目
字符串替換要求:將所有字符串中的空格換成%20,如“how are you”要換成"how%20are%20you"
2.解法
解法一:從前到後複製:時間複雜度爲O(n^2)的解法,從前都後原地複製字符串,由於是原地複製,所以在計算好新字符串長度之後,從前到後複製就要求原字符串中有一個空格,空格後面的所有字符就要向後移動兩位,時間複雜度過大,太麻煩
解法二:從後到前複製,時間複雜度爲O(n)這個方法有個好處就是不用移動字符串,直接從舊的位置複製到新的位置,因爲是從後向前複製,如果後邊開始出現了空格,也是按照計算好的把%20填充進去,並不影響前邊未複製的字符
void replace(char str[], int length)
{
/*記得驗證參數的合法性*/
if( str==NULL && length<0)
{
return;
}
int len = length;//爲原始字符串的長度
int i = len;
int len2 = 0; //替換後的字符串應有的長度
int count=0; // 空格的個數
while(i--)
{
if(str[i] == ' ')
{
count++;
printf("第%d\n",i);
}
}
len2 = len+(count*2); //用一個空格替換三個字符,增多了2個空間
int j = len2;
i = len;
//printf("%d\n",len);
//printf("%d\n",len2);
for( j ; j>=0 ;j--)
{
if(str[i] != ' ')
{
str[j] = str[i];
i--;
}else{
str[j] = '0';
str[j-1] = '2';
str[j-2] = '%';
j = j-2;//原字符串用一個字符替換了三個字符,新字符串減少了2
i--; //注意新字符串長度j減小的同時,原字符串的長度也要隨之減小
}
}
}
int main()
{
char str[] = "how are you";
replace(str,12);
puts(str);
}
3.測試
how are you:
由於參數length在傳遞中我給寫成了12,所以每換一個字符串就得改一下,很麻煩,結合書裏改進一下代碼,把for循環代碼改成while循環
void replace(char str[], int length)
{
/*記得驗證參數的合法性*/
if( str==NULL && length<0)
{
return;
}
int len = length;//爲原始字符串的長度
int i = len;
int len2 = 0; //替換後的字符串應有的長度
int count=0; // 空格的個數
while(i--)
{
if(str[i] == ' ')
{
count++;
}
}
len2 = len+(count*2); //用一個空格替換三個字符,增多了2個空間
int j = len2;
i = len;
while( i>=0 && j>i )
{
if( str[i] == ' ')
{
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
}else{
str[j--] = str[i];
}
--i;
}
}
int main()
{
char str[] = "what a good girl";
replace(str,sizeof(str));
puts(str);
}
測試用例:what a good girl
結果: