题目
请实现一个函数,把字符串中的每个空格替换成%20, 例如 we are happy 输出 we%20are%20happy
思路
1.如果从头开始遍历一遍,遇到空格替换为%20,在将后面的所有向后移动2个单位,依次类推,造成的结果是越是后面有空格的字符串越是移动的次数越多,时间复杂度为O(N*N),如果一次就移动到合适的位置,此问题就会简化。
2.遍历一遍字符串,找出空格数,推断出,将来字符串最大的下标位置,从后向前每个字符串只需移动一次,就移动到合适的位置,时间复杂度为O(n)
代码
/*
请实现一个函数,把字符串中的每个空格替换成%20, 例如 we are happy 输出 we%20are%20happy
*/
#include<stdio.h>
#include<string.h>
void replaceSpace(char *str);
int getp2Index(char *str);
int getp2Index(char *str){
int index = 0;
int p2 = strlen(str)-1;
int spaceCount = 0;
for(index = 0; str[index]; index++){
if(str[index] == ' '){
spaceCount++;
}
}
p2 = p2+2*spaceCount;
return p2;
}
void replaceSpace(char *str){
int p1 = strlen(str)-1;
int p2 = getp2Index(str);
while(p1 >= 0){
while(str[p1] != ' ' && p1 >= 0){
str[p2--] = str[p1--];
}
str[p2] = '0';
str[--p2] = '2';
str[--p2] = '%';
p2--;
p1--;
}
}
int main(){
char str[80] = {0};
printf("请输入要替换的字符\n");
gets(str);
replaceSpace(str);
printf("替换后的字符串如下\n");
printf("%s", str);
return 0;
}