剑指offer5-替换空格
请实现一个函数,把字符串中的每个空格替换成"%20"。
你可以假定输入字符串的长度最大是1000。
注意输出字符串的长度可能大于1000。
样例
输入:"We are happy."
输出:"We%20are%20happy."
思路:
1、思路简单,看代码就懂,碰到空格就替换,python的话也可以直接用str.replace(" “, " %20”);
2、若是用数组或者C语言,这一类,需要先遍历一遍数组,计算出有多少个空格,然后从固定的位置从后往前遍历数组,碰到空格的时候替换为“%20”。
AcWing-16 C++ code:
class Solution {
public:
string replaceSpaces(string &str) {
string res = "";
for(auto x : str){
if(x == ' '){
res += "%20";
}else{
res += x;
}
}
return res;
}
};
牛客网 C++ code :
class Solution {
public:
void replaceSpace(char *str,int length) {
int space_count = 0;
for(int i = 0; i < length; i++){
if(str[i] == ' '){
space_count++;
}
}
int right_index = space_count * 2 + length - 1;
for(int i = length - 1; i >= 0; i--){
if(str[i] == ' '){
str[right_index--] = '0';
str[right_index--] = '2';
str[right_index--] = '%';
}else{
str[right_index--] = str[i];
}
}
}
};
AcWing-16 python code:
class Solution(object):
def replaceSpaces(self, s):
"""
:type s: str
:rtype: str
"""
res = ""
n = len(s)
for i in range(n):
if s[i] == ' ':
res += "%20"
else:
res += s[i]
return res