topic
Please implement a function, a string to replace each space to "20%." For example, when the string is We Are Happy. After the string is replaced after We% 20Are% 20Happy.
Thinking
Since this problem is to char pointer parameter can not be used directly replace method of string, but others reference solution to a problem, found a more clever two-pointer, the method does not create additional string.
reward
Double pointer, the pointer points to the end of the original series 1, 2 just after the pointer at the end of the original string expansion, then decreasing jointly, 1 == pointer when the pointer is 2, indicating that the replacement is successful, the case only because there is no space, double pointer to overlap.
Code
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str==NULL) return ;
int CountOfSpace = 0;
int OriginSize = 0;
for(int i = 0;str[i]!='\0';i++){
OriginSize++;
if(str[i]==' ')
CountOfSpace++;
}
int len = OriginSize+2*CountOfSpace;
if(len+1>length) return ;
char *pstr1 = str+OriginSize;//结束符
char *pstr2 = str+len;
while(pstr2>pstr1){
if(*pstr1==' '){
*pstr2-- = '0';
*pstr2-- = '2';
*pstr2-- = '%';
}
else *pstr2--=*pstr1;
pstr1--;
}
}
};