leetcode Day24 哈希表

62 阅读1分钟

1160. 拼写单词

var countCharacters = function(words, chars) {
    let map=new Map()
    let res=0
    for(let i of chars){
        map.set(i,map.has(i)?map.get(i)+1:1)
    }
    for(let j of words){
        if(check(j,new Map(map))){
            res+=j.length
        }
    }
    return res
};

const check=(j,map)=>{
    for(let i=0;i<j.length;i++){
            if(map.has(j[i]) && map.get(j[i])>0){
                map.set(j[i],map.get(j[i])-1)
            }else{
                return false
            }
        }
        return true
}

1189. “气球” 的最大数量

var maxNumberOfBalloons = function(text) {
    let str='balloon'
    let map=new Map()
    for(let i of text){
        if(str.includes(i)){
            if(i==='l' || i==='o'){
                map.set(i,map.has(i)?map.get(i)+0.5:0.5)
            }else{
                map.set(i,map.has(i)?map.get(i)+1:1)
            }
        }
    }
    if(map.size<5){
        return 0
    }else{
        let arrayObj=Array.from(map);
        arrayObj.sort((a,b)=> a[1]-b[1])
        return Math.floor(arrayObj[0][1])
    }
};

1207. 独一无二的出现次数

var uniqueOccurrences = function(arr) {
    let map=new Map()
    let res=[]
    for(let i of arr){
        map.set(i,map.has(i)?map.get(i)+1:1)
    }
    for(let [key,value] of map){
        res.push(value)
    }
    if(res.toString()===[...new Set(res)].toString()){
        return true
    }
    return false
};