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

如何在JavaScript/TypeScript中获取最长连续字符的索引?

获取字符串中最长连续字符的索引(TypeScript实现)

你的代码逻辑存在几个问题:idx数组的收集方式会重复添加同一连续序列的多个索引,且未正确处理字符串末尾的连续段,导致结果不符合预期。以下是修正后的实现:

const value: string = 'ABCCCCCDDBEAAA';

function longest(str: string) {
  let maxLength = 0;
  let currentLength = 1;
  let longestChar = '';
  let currentStartIdx = 0;
  let longestIndices: number[] = [];

  for (let i = 0; i < str.length; i++) {
    const current = str[i];
    const next = str[i + 1];

    if (current === next) {
      currentLength++;
    } else {
      // 对比当前连续序列与最长序列
      if (currentLength > maxLength) {
        maxLength = currentLength;
        longestChar = current;
        // 生成当前连续段的所有索引
        longestIndices = Array.from({ length: currentLength }, (_, idx) => currentStartIdx + idx);
      } else if (currentLength === maxLength) {
        // 若存在多个长度相同的最长序列,合并索引(可根据需求改为保留第一个)
        const currentIndices = Array.from({ length: currentLength }, (_, idx) => currentStartIdx + idx);
        longestIndices = [...longestIndices, ...currentIndices];
      }
      // 重置当前序列状态
      currentLength = 1;
      currentStartIdx = i + 1;
    }
  }

  // 处理字符串末尾的最后一段连续序列
  if (currentLength > maxLength) {
    maxLength = currentLength;
    longestChar = str[str.length - 1];
    longestIndices = Array.from({ length: currentLength }, (_, idx) => currentStartIdx + idx);
  } else if (currentLength === maxLength) {
    const currentIndices = Array.from({ length: currentLength }, (_, idx) => currentStartIdx + idx);
    longestIndices = [...longestIndices, ...currentIndices];
  }

  return { maxLength, longestChar, longestIndices };
}

console.log(longest(value));
// 输出:{ maxLength: 5, longestChar: 'C', longestIndices: [2, 3, 4, 5, 6] }

关键改进说明

  • 新增currentStartIdx跟踪当前连续序列的起始位置,方便生成完整的索引列表
  • 在连续序列结束时(遇到不同字符)统一对比长度,避免原代码中多次重复添加索引的问题
  • 补充处理字符串末尾的连续段,确保不会遗漏最后一段可能的最长序列
  • 变量命名更直观(如max改为maxLength),提升代码可读性

原代码问题点

  • idx.push(i)会在每次currentMax > max时执行,导致同一连续序列的每个索引被重复添加,且未重置数组
  • 未处理字符串末尾的连续序列,可能导致最长序列被遗漏
  • 逻辑判断时机不合理,导致索引收集错误

内容的提问来源于stack exchange,提问作者Imran Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:15:40