题目描述:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路: 逆向遍历
1.由于函数返回为void,说明此题不能另外开辟数组,需要in-place操作。我们知道字符串的遍历无非是从左到右和从右到左两种。
1)如果从左到右,会发现如果遇到空格,会将原来的字符覆盖。于是,此方法不行。
2)那么就考虑从右向左,遇到空格,就填充“20%“,否则将原字符移动应该呆的位置。
代码:(c++版)
class Solution {
public:
void replaceSpace(char *str,int length) {
//先判断字符串是否为空
if (str == nullptr || length <= 0) return;
//统计空格的个数
int countSpace = 0;
for(int i=0;i != length ; ++i)
{
if(str[i] == ' ') ++countSpace;
}
if(!countSpace) return ;//无空格直接返回
int new_length = length+countSpace*2; //新的长度= 原来的长度+空格的个数*2
for(int i = length ; i>=0;--i){
if(str[i]==' ')
{
str[new_length--]='0';
str[new_length--] = '2';
str[new_length--] = '%';
}
else{
str[new_length--] = str[i];
}
}
}
};
代码二:(python 版)
python中自带的有内置函数,直接进行替换:str.replace(" ",'str1')
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here 使用内置函数直接替代。
return s.replace(" ",'%20')