【leetcode】LCP 66. Minimum number of booths (implemented by js)

1. Topic

LCP 66. Minimum number of booths
insert image description here

2. Idea

  1. First count the number of booths needed each day;
  2. Then select the maximum number of booths of each type;
  3. Finally, add the maximum number of each booth and return.
  • Taking test case 1 as an example, it will be easier to understand with this picture.
    insert image description here

3. Code implementation

/**
 * @param {string[]} demand
 * @return {number}
 */
var minNumBooths = function(demand) {
    
    
    // 索引为字母在字母表中的位置,值为出现的个数
    let arr = new Array(26).fill(0) 
    for (let str of demand) {
    
    
        let map = new Map()
        for (let i = 0; i < str.length; i++) {
    
    
            let key = str.charCodeAt(i) - 97
            map.set(key, (map.get(key) || 0) + 1)
        }
        for (let [key, val] of map) {
    
    
            arr[key] = Math.max(val, arr[key])
        }
    }
    let cnt = 0
    arr.forEach(item => cnt += item)
    return cnt
};

4. Reference

[Han Ergou] Go/Java/JavaScript Hash + Analog Double Hundred

Guess you like

Origin blog.csdn.net/weixin_44109827/article/details/129416999