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

如何使用JavaScript查找字符串中最大的5位连续数字序列

实现方案

你可以基于现有分割后的块数组,通过比较块对应的数值大小取出最大值即可,完整实现如下:

function solution(digits){
  // 按每5位非重叠分割为块
  const chunks = digits.match(/.{1,5}/g);
  // 过滤掉长度不足5位的块(字符串总长度不是5的倍数时会产生),再取最大值
  const maxChunk = chunks
    .filter(chunk => chunk.length === 5)
    .reduce((max, current) => Number(current) > Number(max) ? current : max, '00000');
  return maxChunk;
}

// 测试示例
const testStr = "731671765313306249192251196744265747423553491949349698352036854250632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895";
console.log(solution(testStr));

如果你需要找的是所有连续5位重叠子串里的最大值(比如字符串"987654"会同时把"98765"、"87654"都纳入候选),可以用以下实现:

function solution(digits) {
  let max = '00000';
  // 遍历所有可能的5位子串起始位置
  for (let i = 0; i <= digits.length - 5; i++) {
    const current = digits.slice(i, i + 5);
    if (Number(current) > Number(max)) {
      max = current;
    }
  }
  return max;
}

内容的提问来源于stack exchange,提问作者Jonathan Joseph

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:39:01