Question Description
Please implement a function that replaces spaces in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.
Time limit: 1 second Space limit: 32768K Heat index: 559991
Knowledge points of this question: String
class Solution {
public:
void replaceSpace(char *str,int length) {
int i=0;
int oldnum=0,newnum=0,basenum=0;
while(str[i]!='\0'){
oldnum++;
if(str[i]==' '){
basenum++;
}
i++;
}
newnum=oldnum+2*basenum;
int p1=oldnum,p2=newnum;
if(newnum>length)
return;
while(p1>=0&&p1<p2){
if(str[p1]==' '){
str[p2--]='0';
str[p2--]='2';
str[p2--]='%';
}
else
str[p2--]=str[p1];
p1--;
}
}
};