【剑指Offer】替换空格

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

算法分析

首先复制一份字符串的备份,我们需要知道字符串原始长度,空格数来计算替换后字符串的长度,之后就只需要根据字符串原始长度和新长度对字符串进行拷贝。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
void replaceSpace(char *str,int length) {
char *t = str;
int strLen = 0, newStrLen = 0, spaceCount = 0;
int p,q;

if(str == NULL || length <0) return; // 首先判定进入算法的有效条件

while(*t != '\0'){
strLen++;
if(*t == ' ') spaceCount++;
t++;
} // 取字符串长度, 空格的个数

newStrLen = strLen + 2 * spaceCount; // 新的字符串的长度
if(newStrLen > length) return ;

for(p = strLen, q = newStrLen; p >= 0; p-- ){
if(str[p] == ' '){
str[q--] = '0';
str[q--] = '2';
str[q--] = '%';
} else {
str[q--] = str[p];
}
}
}
};