码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithm] Max Chars Problem

时间:2019-05-31 23:58:50      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:most   number   expec   return   ===   rac   sed   problem   numbers   

// --- Directions
// Given a string, return the character that is most
// commonly used in the string.
// --- Examples
// maxChar("abcccccccd") === "c"
// maxChar("apple 1231111") === "1"

function maxChar(str) {
  let m = {},
    max = -1,
    result = null;

  for (let char of str) {
    m[char] = m[char] + 1 || 1;
  }

  for (let [key, count] of Object.entries(m)) {
    max = Math.max(max, count);
    if (max === count) {
      result = key;
    }
  }

  return result;
}

module.exports = maxChar;

  

const maxChar = require(‘./index‘);

test(‘maxChar function exists‘, () => {
  expect(typeof maxChar).toEqual(‘function‘);
});

test(‘Finds the most frequently used char‘, () => {
  expect(maxChar(‘a‘)).toEqual(‘a‘);
  expect(maxChar(‘abcdefghijklmnaaaaa‘)).toEqual(‘a‘);
});

test(‘Works with numbers in the string‘, () => {
  expect(maxChar(‘ab1c1d1e1f1g1‘)).toEqual(‘1‘);
});

  

[Algorithm] Max Chars Problem

标签:most   number   expec   return   ===   rac   sed   problem   numbers   

原文地址:https://www.cnblogs.com/Answer1215/p/10957803.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!