题目:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。
解题思路:以时间效率优先的话,可以分为两种处理办法,一种利用辅助内存,即新开辟一个数组,时间复杂度为O(n)
另一种不用辅助内存,即在原数组上操作:
1.先遍历一次数组,统计空白字符个数,记录在blankcount中,数组的最后一位‘ ’的下标记录在index中;
2.求得替换空格后的数组最后一位下标lastindex=index+2*blankcount;
3.从后往前遍历数组,替换数组中的空格。
实现代码如下:
#include<iostream> #include<string> using namespace std; void replace(char *array,int length) { if(array!=NULL&&length>0)//判断参数是否合法 { int blankcount=0,index=0;//blankcount记录空格数,index记录数组中最后一为' '的下标 while(array[index]!='