前端面试题 题目:找到字符串中连续最多的那个字符: 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]

你可能感兴趣的:(前端面试题 题目:找到字符串中连续最多的那个字符: aabbbbbaccchh -> bbbbb)