habc0807 / fe-interview

BAT、TMD等各大厂中高级、资深前端面试题整理
36 stars 4 forks source link

统计字符串中出现最多的字母与个数? #76

Open habc0807 opened 4 years ago

habc0807 commented 4 years ago

var str = ‘wodexiaomaojiaoxiaohei’;

zhump commented 2 years ago

'wodexiaomaojiaoxiaohei'.split('').sort().join('').match(/(.)\1+/g).sort((a,b)=>b.length-a.length)[0]

kayac-chang commented 7 months ago
const str = "wodexiaomaojiaoxiaohei";

function fn(str) {
  if (!str.length) return;

  str = str.split("").sort();

  let left = 0;
  let char = str[left];
  let max_len = 0;

  for (let right = 1; right < str.length; right++) {
    if (str[right - 1] !== str[right]) {
      if (right - left > max_len) {
        max_len = right - left;
        char = str[right - 1];
      }
      left = right;
    }
  }

  return [char, max_len];
}

console.log(fn(str));