原文:找出字符串中连续出现最多的字符和个数 - 每天一个JavaScript小知识@Js中文网 · 码农进阶题库

原文地址:https://www.javascriptc.com/interview-tips/zh_cn/javascript/look-for-more-string/

题目描述:

找出字符串中连续出现最多的字符和个数

'abcaakjbb' => {'a':2,'b':2}
'abbkejsbcccwqaa' => {'c':3}

知识点:

  • 我们可以通过正则匹配到字符串中连续出现的字符
  • ”(.)(\1)+”。即可找出对应的字符串。.表示匹配任意连续出现的字符串,也可以指定你想要匹配的项。

解题:

  • 思路一: ```javascript 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);


+ 思路二:
+ 比较暴力的方法解决

```javascript
function findLongest(str) {
  if (!str) return {}
  let count = 0
  let maxCount = 0
  let cur = str[0]
  let res = {}
  for (let i = 0; i < str.length; i++) {
    const s = str[i]
    if (s === cur) {
      count++
      if (count > maxCount) {
        res = { [s]: count }
        maxCount = count
      }
      if (count === maxCount) {
        res[s] = count
      }
    } else {
      count = 1
      cur = s
    }
  }
  return res
}
  • 思路三:
    const arr = str.match(/(.)\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) // {c: 3}
    

扩展阅读: