qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!

Home Page:https://github.com/qappleh/Interview

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

第11题(2019-08-05): 编程题,找出字符串中连续出现最多的字符和个数

qappleh opened this issue · comments

commented
'abcaakjbb' => {'a':2,'b':2}
'abbkejsbcccwqaa' => {'c':3}  
commented
const arr = str.match(/(\w)\1*/g);
const maxLen = Math.max(...arr.map(s => s.length));
const result = arr.reduce((pre, curr) => {
  if (curr.length === maxLen) {
    pre[curr[0]] = curr.length;
  }
  return pre;
}, {});
console.log(result);
commented

不考虑空间和时间复杂度,- .. -

function findMost(str) {
  const m = new Map();
  for (let s of str) {
    if (m.has(s)) {
      m.set(s, m.get(s) + 1);
    } else {
      m.set(s, 1);
    }
  }

  const maxValue = Math.max.apply(null, [...m.values()]);
  let res = {};
  for (let [k, v] of m.entries()) {
    if (maxValue === v) {
      res[k] = v;
    }
  }

  return res;
}