请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解:遇到该题目最直接的想法就是先计算出空格数目,然后新开辟一个数组用来存储新的字符串,无赖最后发现牛客网提供接口为void,所以不可能通过开辟新的数组来实现。所以就只能在原数组上实现
c++实现代码:
class Solution {
public:
void replaceSpace(char *str,int length) {
if (str == NULL || length <= 0)
return;
int cnt = 0;
for(int i = 0;i < length;i++)
{
if(str[i] == ' ')
cnt++;
}
int new_length = length + 2 * cnt - 1;
for(int i = length - 1;i >= 0;i--)
{
if(str[i] == ' ')
{
str[new_length--] = '0';
str[new_length--] = '2';
str[new_length--] = '%';
}
else{
str[new_length--] = str[i];
}
}
}
};
python实现:
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
result = ''
if len(s) == 0:
return result;
for c in s:
if c == ' ':
result += '%20'
else:
result += c
return result