Find the most consecutive character in the string: aabbbbbaccchh -> BBBBB

The interview was done in a very complicated way, in code

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');
Copy the code

Then an easier way was found

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]
Copy the code