題目描述
請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
解題思路
首先計算字符串中的空格數量,若空格數量爲count,則替換後的字符串長度增加2*count;
然後從最後一位開始替換字符,若爲空格,則依次從後往前替換爲’0’ ‘2’ ‘%’,否則不變;
由於已經知道了空格的數量,因此在替換完最後一個空格(即從前往後數第一個)之後,則可以停止替換,剩下的字符保持不變即可。
代碼
class Solution {
public:
void replaceSpace(char *str, int length) {
//find space num
int count = 0;
for (int i = 0; i < length; i++) {
if (str[i] == ' ')
count++;
}
int new_length = length + 2 * count;
int j = new_length - 1;
for (int i = length - 1; i >= 0; i--) {
if (count == 0)
break;
if (str[i] == ' ') {
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
count--;
}
else {
str[j--] = str[i];
}
}
}
};