zoukankan      html  css  js  c++  java
  • [Algorithm] Max Chars Problem

    // --- 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');
    });
    

      

  • 相关阅读:
    LIS
    原根
    数三角形
    组合数问题
    最短路问题
    2020总结
    树状数组
    康托展开
    LCA
    并查集
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10957803.html
Copyright © 2011-2022 走看看