问题:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:从前往后移动,移动的次数太多,从后往前移动,移动的次数刚好!
class Solution { public: void replaceSpace(char *str,int length) { if(str==NULL||length<0) return ; int spacecnt=0; int i=0; int oldLength=0; while(str[i]!='\0') { oldLength++; if(str[i]==' ') spacecnt++; i++; } int newLength=oldLength+2*spacecnt; if(newLength>length) return ; int p1=oldLength; int p2=newLength; while(p1>=0&&p2>p1) { if(str[p1]==' ') { str[p2--]='0'; str[p2--]='2'; str[p2--]='%'; } else { str[p2--]=str[p1]; } p1--; } return ; } };