晨敛清荷

文章 评论 浏览 28

晨敛清荷 2022-05-04 13:56:16

题目可以再加一个:堆叠上下文(The stacking context)

第 73 题: 介绍下 BFC、IFC、GFC 和 FFC

晨敛清荷 2022-05-04 13:55:09

看大佬们都使用正则表达式进行匹配,小弟就不用正则来个版本

主要思路如下:

  1. 想要计算出现的次数,则需要遍历,这里通过Array.prototype.reduce方法,遍历每一个字符

  2. 题目又说是连续出现,那么只要单个字符出现2次以上,就要储存,所以这里在遍历的时候,通过reduce的第二个参数保存一个temp对象。

  3. 根据temp中该字符重复出现的次数就行逻辑判断。

    如果一旦发现temp对象中不存在[next]属性,则表示next并不是连续字符,所以完全覆盖temp对象

  4. 结果出来以后,删除strToObj中的temp属性。

  5. 通过Math.max以及Object.values方法找出最大值max

  6. filter对象strToObj,找出值等于max的。

  7. 最后在使用reduce拼接结果返回。

const findMaxRepeatString = str => {
  if (typeof str !== 'string') return {};
  const strToObj = Array.prototype.reduce.call(
    str,
    (pre, next) => {
      let track = pre.temp[next];
      if (!track) {
        pre.temp = {
          [next]: 1,
        };
        return pre;
      }
      track = ++pre.temp[next];
      if (track < 2) return pre;
      const v = track - (pre[next] || 0);
      pre[next] = v >= 1 ? track : pre[next];
      return pre;
    },
    { temp: {} }
  );
  delete strToObj.temp;
  const max = Math.max(...Object.values(strToObj));
  if (max < 2) return {};
  return Object.keys(strToObj)
    .filter(key => strToObj[key] === max)
    .reduce((pre, key) => {
      pre[key] = strToObj[key];
      return pre;
    }, {});
};

findMaxRepeatString ('aa11bbbppbbb'); // { b: 3 }

第 114 题:找出字符串中连续出现最多的字符和个数

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文