You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS查找字符串所有换行符索引时丢失匹配结果该如何优化?

问题原因分析

你编写的双指针代码存在两个核心问题:

  • 循环条件使用l < r,漏掉了l与r重合位置的字符检查:比如单换行符的字符串a\nb,换行符位于索引1,当l和r都移动到1时循环直接终止,不会检查该位置字符,因此返回空数组,你示例中第一个换行索引20漏检也是同理。
  • 双指针从两端向中间扫描的逻辑会导致索引添加顺序混乱,需要额外排序,性能低于常规顺序遍历。
优化方案

方案1:修复原有双指针逻辑

调整循环条件,避免漏检中间位置的字符:

const findNewLineCharacterIndex = (s) => {
    let l = 0; let r = s.length - 1;
    const arr = [];
    const cmp = (char) => char === '\n' || char === '\r';
    while (l <= r) {
        if (l === r) {
            if (cmp(s[l])) arr.push(l);
            break;
        }
        if (cmp(s[l])) arr.push(l);
        if (cmp(s[r])) arr.push(r);
        l += 1;
        r -= 1;
    }
    arr.sort((a, b) => a - b);
    return arr;
};

方案2:顺序遍历(更简单,无额外排序开销)

const findNewLineCharacterIndex = (s) => {
    const res = [];
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '\n' || s[i] === '\r') {
            res.push(i);
        }
    }
    return res;
};

方案3:基于indexOf循环查找(长字符串性能优异)

如果你想用indexOf实现全量查找,可以循环调用并指定下一次查找的起始位置:

const findNewLineCharacterIndex = (s) => {
    const res = [];
    let pos = s.indexOf('\n');
    while (pos !== -1) {
        res.push(pos);
        pos = s.indexOf('\n', pos + 1);
    }
    // 如需同时匹配\r,可补充对\r的查找逻辑,或直接使用正则方案:
    // return [...s.matchAll(/[\r\n]/g)].map(item => item.index)
    return res;
};

以上任意方案都可以得到你期望的结果[20, 34, 82, 119, 179, 232, 303, 352],同时支持单个换行符的场景。

内容的提问来源于stack exchange,提问作者STEPHEN bui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 14:45:05