题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
string replaceSpace(string iniString, int length)
{
string newString;
for(int i=0;i<length;i++)
{
if(iniString[i]==' ')
{
newString=newString+"%20";
continue;
}
newString+=iniString[i];
}
return newString;
}
};
您的代码已保存
段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
上述代码其实是把接口部分改变了,但是没明白为什么会越界。
思路:从前向后记录‘ ’数目,从后向前替换‘ ’。 重点:从后向前替换的时候的技巧 例如:“we are lucky”
0 1 2 3 4 5 6 7 8 9 10 11
w e a r e l u c k y
可以得知count=2;//空格的个数。 所以在替换的时候7~11的字母要向后移动count×2个位置,3~5字母要向后移动(count-1)×2个位置。 所以得到 :
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
w e a r e l u c k y
w e a r a r e u c k l u c k y
在替换的时候直接在空格处写入%20了
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
w e a r e l u c k y
w e % 2 0 a r e % 2 0 l u c k y
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';
}
}
}
};
//思路
//1:从前往后插入,这样移动·的次数多不建议
//2:从后往前插入
class Solution {
public:
void replaceSpace(char *str,int length) {
//遍历一边字符串找出空格的数量
if(str==NULL||length<0)
return ;
int i=0;
int oldnumber=0;//记录以前的长度
int replacenumber=0;//记录空格的数量
while(str[i]!='\0')
{
oldnumber++;
if(str[i]==' ')
{
replacenumber++;
}
i++;
}
int newlength=oldnumber+replacenumber*2;//插入后的长度
if(newlength>length)//如果计算后的长度大于总长度就无法插入
return ;
int pOldlength=oldnumber; //注意不要减一因为隐藏个‘\0’也要算里
int pNewlength=newlength;
while(pOldlength>=0&&pNewlength>pOldlength)//放字符
{
if(str[pOldlength]==' ') //碰到空格就替换
{
str[pNewlength--]='0';
str[pNewlength--]='2';
str[pNewlength--]='%';
}
else //不是空格就把pOldlength指向的字符装入pNewlength指向的位置
{
str[pNewlength--]=str[pOldlength];
}
pOldlength--; //不管是if还是elsr都要把pOldlength前移
}
}
};
拥抱明天!
不给自己做枷锁去限制自己。
别让时代的悲哀,成为你人生的悲哀。

浙公网安备 33010602011771号