题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
第一种思路,开辟一个新的内存存修改后的字符串(时间复杂度为o(n))
class Solution {
public:
void replaceSpace(char *str,int length) {
const int maxn = 100000+1;
char nowStr[maxn] = {'1'};
int count = 0;
for(int i = 0;i < length;++i)
{
if(str[i] == ' ')
{
nowStr[count++] = '%';
nowStr[count++] = '2';
nowStr[count++] = '0';
}
else
nowStr[count++] = str[i];
}
strcpy(str,nowStr);
}
};
第二种思路:从后往前搜,遇到空格原字符串整体向后移三格,用来填充%20
class Solution {
public:
void replaceSpace(char *str,int length) {
int i=length-1,j,count=0;
while(i>=0){ //从后往前扫描字符串
if(str[i]==' '){ //如果扫描到字符是空格
for(j=length;j>=i;j--){ //将字符串从空格到最后的'\0'都往后移动两个位置,因为要塞 %20
str[j+2]=str[j];
}
str[i]='%'; //i就是空格的位置,放%
str[i+1]='2'; //i+1放2
str[i+2]='0'; // i+2放0
length+=2; //长度要加二
}
i--;
}
};