替换字符串中的空格
劍指offer面試題
請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串為We Are Happy.則經過替換之后的字符串為We%20Are%20Happy。
看到題目后的思路
看到這個題目后,我們首相應該想到的是:原來的一個空格字符,經過替換后就成了三個字符,因此字符會變長,那么很有可能會覆蓋原來的字符。如果是在一個新創建的字符串上做替換,就可以有足夠的空間,顯然題目上沒有明顯的提出,那就應該在原來的字符串上做替換
偽代碼實現
思維圖
(圖片來源《劍指offer》)
c++代碼實現
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;} };總結
- 上一篇: Lambda 表达式详解~Lambda与
- 下一篇: 王爽 汇编语言第三版 第7章 --- 更