题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:
水题!
1.另外开辟一个字符串new_s,遍历s,把s赋值给new_s。空间复杂度O(n)。
2.两个指针。
代码1:
class Solution:
# s 源字符串
def replaceSpace(self, s):
res = ''
for i in s:
if i == ' ':
res += '%20'
else:
res += i
return res
代码2:
class Solution {
public:
void replaceSpace(char *str,int length) {
//统计空格个数
int spaceCount = 0;
int i = 0;
for (i = 0; i < length; i ++){
if(str[i] == ' ')
spaceCount ++;
}
int newLength = length + spaceCount * 2;//新长度
int leftindex = length - 1;
int rightindex = newLength - 1;
while(leftindex >= 0){
if(str[leftindex--] == ' '){
str[rightindex--] = '0';
str[rightindex--] = '2';
str[rightindex--] = '%';
}else{
str[rightindex--] = str[leftindex + 1];
}
}
}
};