时间限制:1秒
空间限制:32768K
热度指数:570770
算法知识视频讲解
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
C++实现:
class Solution {
public:
void replaceSpace(char *str,int length) {
int count=0;
for(int i=0;i<length;i++){
if(str[i]==' ')
count++;
}
for(int i=length-1;i>=0;i--){
if(str[i]!=' '){
str[i+2*count]=str[i];
}
else{
count--;
str[i+2*count]='%';
str[i+2*count+1]='2';
str[i+2*count+2]='0';
}
}
}
};
Python 实现:
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
a = len(s)
b = []
for i in range(0, a):
if s[i] == ' ':
b.append(i)
flag = 2
for i in range(0, len(b)):
s = s[0:b[i] + flag * i] + "%20" + s[b[i] + flag * i + 1 :]
return s
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s = s.replace(' ', '%20')
return s