題目描述
請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str == NULL || length < 0) return;
int old_length = 0, new_length = 0;
int num = 0;
for(int i = 0; str[i] != '\0'; ++i)
{
old_length++;
if(str[i] == ' ') ++num;
}
new_length = old_length + 2 * num;
if(new_length > length) return;
int pold = old_length; // char[] 字符串數組長度需要把結束符‘\0’算入其中,old_length的值指的是字符元素數量加上'\0'的數量
int pnew = new_length;
while(pold >= 0)
{
if(str[pold] != ' ')
{
str[pnew] = str[pold];
pnew--;
}
else
{
str[pnew--] = '0';
str[pnew--] = '2';
str[pnew--] = '%';
}
pold--;
}
}
};
思路:遍歷計算原長度和空格數目;計算新長度;判斷新長度是否符合;從後往前遍歷對數組進行更新【這樣的話比從前往後移動的次數少】