Skip to content

Latest commit

 

History

History
64 lines (53 loc) · 1.71 KB

05. 替换空格.md

File metadata and controls

64 lines (53 loc) · 1.71 KB

题目链接:

剑指 Offer 05. 替换空格

思路:

这道题可以用很简单的方法实现,比如:

const replaceSpace = s => s.split(' ').join('%20');

或者直接用replace也可以。

但要我们自己手动实现的话,可以使用双指针解法

  1. 先统计空格数量
  2. 字符串转化为数组,更新数组长度
  3. 定义双指针:left:旧长度-1、right:新长度-1
  4. 从后往前遍历,如果左指针遇到空格,右指针依次填入%20,并左移2
  5. 如果左指针遇到字符,直接将左指针的值赋给右指针
  6. 左指针和右指针还有分别左移1
  7. 最后返回字符串

代码:

JavaScript

const replaceSpace = s => {
    // 转化为数组
    const arr = s.split('');
    // 统计空格数量
    let spaceCount = 0;
    const len = arr.length;
    for (let i = 0; i < len; i++) {
        if (arr[i] === ' ') spaceCount++;
    }
    // 更新数组长度,每个空格,要多出2个位置
    arr.length += 2 * spaceCount;
    // 定义双指针
    // left:旧长度-1
    // right:新长度-1
    let [left, right] = [len - 1, arr.length - 1];
    while (left >= 0) {
        if (arr[left] !== ' ') {
            // 如果遇到字符,直接将左指针的值赋给右指针
            arr[right] = arr[left];
        } else {
            // 遇到空格,依次填入%20,右指针左移2
            arr[right - 2] = '%';
            arr[right - 1] = '2';
            arr[right] = '0';
            right -= 2;
        }
        // 分别左移1
        left--;
        right--;
    }
    // 返回字符串
    return arr.join('');
};