請實現一個函數,將一個字符串中的每個空格替換成「%20」。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
看到這個題目後,我們首相應該想到的是:原來的一個空格字符,經過替換後就成了三個字符,因此字符會變長,那麼很有可能會覆蓋原來的字符。如果是在一個新創建的字符串上做替換,就可以有足夠的空間,顯然題目上沒有明顯的提出,那就應該在原來的字符串上做替換
(圖片來源《劍指offer》)
class Solution { public: void replaceSpace(char *str, int length) { if (str == NULL && length <= 0) return; //如果是空直接返回 int factlength = 0; //實際字符數 int spacenumber = 0; //字符串中空格的數量 int i = 0; while (str[i] != '\0') { ++factlength; if (str[i] == ' ') { ++spacenumber; } ++i; } //擴展第二個字符串, //空格的數量*2是因爲「%20」一共三個字符,需要在原來每個空格的位置再加上兩個字符的長度,纔是第二個字符串的 int newlength = factlength + spacenumber * 2; if (newlength > length) { return; } //從後向前替換,這樣會減少替換的次數 char *pStr1 = str + factlength; char *pStr2 = str + newlength; //如果pStr2 <= pStr1 了,說明剩下的pStr2和pStr1的字符串相同了,也就沒有「 」了,就不用替換了 while (pStr2 > pStr1 && pStr1 >= 0) { if (*pStr1 == ' ') { *pStr2-- = '0'; *pStr2-- = '2'; *pStr2-- = '%'; } else { *pStr2-- = *pStr1; } --pStr1; } return; } };