剑指offer5. 替换空格 P51

mac2024-04-21  5

剑指offer 5. 替换空格 P51

1. 第一种做法可以用sting = “”,遍历原始数组,遇到非空格直接加,遇到空格加上%20,最后string就是答案。 这种做法比较简洁易懂,但是空间复杂度是O(N)

2. 第二种做法就是书上的用两个指针倒着工作。在原地操作,空间开销小

void replaceBlank(char string[], int length) { if (string == NULL || length <= 0) return; int count = 0, old_tail = 0; // 记录空格数;原数组索引指针 while (string[old_tail] != '\0') { if (string[old_tail] == ' ') ++count; old_tail++; } // 新数组结尾 int new_tail = old_tail + count * 2; //不是*3,因为原来的空格还可以放一个 if (new_tail > length) return; //不能=, 因为’\0’ while (old_tail >= 0) { // 两个指针一起倒着走 if (string[old_tail] != ' ') string[new_tail--] = string[old_tail]; else { string[new_tail--] = '0'; string[new_tail--] = '2'; string[new_tail--] = '%'; } old_tail--; //不能在if里面减 } }

扩展: 有两个从小到大排序数组a,b。 a尾部有足够的空间容纳b,试着把b合并到a中,并且保持依然有序。

思想:跟这题很像,可以确定a的新结尾len(a)+len(b) – 1;然后倒着遍历两数组,把较大的放入新结尾,更新工作指针。

最新回复(0)