记一道前端面试题->找到字符串中连续最多的那个字符

题目:找到字符串中连续最多的那个字符: aabbbbbaccchh -> bbbbb

面试时用了很复杂的方式来实现,上代码

const findStrMaxLength = (str) => {
  let max = 1;
  let resultKey; 
  let array = str.split('');
  let mapArray = array.map(item => {
    return {num: 1, key: item}
  });
  for (let i = array.length - 1; i > 0; i--) {
    if (mapArray[i].key === mapArray[i - 1].key) {
      mapArray[i].num++;
      mapArray[i - 1].num = mapArray[i].num;
      mapArray.splice(i, 1)
    }
  }

  for (let i of mapArray) {
    if (i.num > max) {
      max = i.num;
      resultKey = i.key
    }
  }
  console.log(mapArray, max, resultKey, resultKey.repeat(max))

};
findStrMaxLength('aabbbbbaccchh');
复制代码

后来找到了更简单的方法

const str = 'aabbbbbaccchh', reg = /(.)\1*/g;
const arr = str.match(reg); // ["aa", "bbbbb", "a", "ccc", "hh"]
arr.sort((a,b)=>{return b.length-a.length})[0]
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值