面试题5:替换空格
题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,则输出“We%20are%20happy.”。
#include<iostream>
using namespace std;
/**
* 首先我们拿到这个题目,开始的想法可能是从头开始遍历字符串,遇到空格进行替换成"%20",
* 但是要将后面的字符串向后移动2个位置,时间复杂度O(n^2)
*
* 我们可以考虑从后面开始遍历,这样先遍历一遍计算字符串长度和空格个数,可以推出最终
* 字符串长度,再用两个索引从后向前遍历即可,时间复杂度O(n)
**/
void ReplaceBlank(char str[], int length) {
if(str==NULL || length<=0) return;
int originalLength=0;
int numOfBlank=0;
int i=0;
while(str[i]!='\0') {
originalLength++;
if(str[i]==' ') numOfBlank++;
i++;
}
int newLength = originalLength + numOfBlank * 2;
if(newLength > length) return;
int idxA=originalLength, idxB=newLength;
while(idxA>=0 && idxB>idxA) {
if(str[idxA]==' ') {
str[idxB--]='0';
str[idxB--]='2';
str[idxB--]='%';
} else {
str[idxB--]=str[idxA];
}
idxA--;
}
}
int main() {
char str[]="We are happy.";
ReplaceBlank(str, 100);
printf("%s", str);
return 0;
}
举一反三
在合并两个数组(包括字符串)时,如果从前往后复制每个数字(或字符)则需要重复移动数字(或字符)多次,那么我们可以考虑从后往前复制,这样就能减少移动的次数,从而提高效率。