剑指offer_05 替换空格
// char *s = “hello”;后,不能使用s[0]=‘a’;语句进行赋值。这是将提示内存不能为"written"
// C语言还是太考验细节的东西了,只要有一步有一点点不对就会报错(堆溢出)
// 因为c语言不能像别的语言一样,在原地扩充数组,所以只能牺牲时间复杂度
1 char* replaceSpace(char* s){ 2 // 统计空格数量 3 int count = 0; 4 int len = strlen(s); 5 for (int i = 0; i < len; i++) { 6 if (*(s+i) == ' ') { 7 count++; 8 } 9 } 10 11 //为新数组分配空间 12 int newLen = len + count * 2; 13 // 因为c语言不能像别的语言一样,在原地扩充数组,所以只能牺牲时间复杂度 14 char* result = malloc(sizeof(char) * newLen + 1); 15 //填充新数组并替换空格 16 for (int i = len - 1, j = newLen - 1; i >= 0; i--, j--) { 17 if (*(s+i) != ' ') { 18 *(result+j) = *(s+i); 19 } else { 20 *(result+j) = '0';j--; 21 *(result+j) = '2';j--; 22 *(result+j) = '%'; 23 } 24 } 25 result[newLen] = '\0'; 26 27 return result; 28 }