fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

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

Open habc0807 opened this issue 3 years ago • 2 comments

var str = ‘wodexiaomaojiaoxiaohei’;

habc0807 avatar Sep 08 '20 14:09 habc0807

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

zhump avatar Nov 17 '21 08:11 zhump

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));

kayac-chang avatar Mar 18 '24 08:03 kayac-chang