[leetcode, JS] 1189. Maximum Number of Balloons

mxxn·2023년 10월 4일
0

leetcode

목록 보기
87/193

문제

문제 링크 : Maximum Number of Balloons

풀이

/**
 * @param {string} text
 * @return {number}
 */
var maxNumberOfBalloons = function(text) {
    const obj = {}
    for(let s of text) {
        obj[s] ? obj[s] += 1 : obj[s] = 1
    }
    let chk = true
    let result = 0
    while(chk) {
        if(obj['b'] > 0 && obj['a'] > 0 && obj['l']>1 && obj['o']>1 && obj['n'] > 0) {
            obj['b'] -= 1
            obj['a'] -= 1
            obj['l'] -= 2
            obj['o'] -= 2
            obj['n'] -= 1
            result += 1
        } else { 
            chk = false
        }
    }
    return result
};
  1. text의 알바펫 개수를 확인하고
  2. 'balloon' 문자열을 만들 수 있는 개수 카운트
  • Runtime 44 ms, Memory 43.3 MB

다른 풀이

/**
 * @param {string} text
 * @return {number}
 */
var maxNumberOfBalloons = function(text) {
    const map = {
        'a': 0,
        'b': 0,
        'l': 0,
        'n': 0,
        'o': 0
    };
    for (let i = 0; i < text.length; i++) {
        if (text[i] in map) map[text[i]]++;
    }
    map['l'] = Math.floor(map['l'] / 2);
    map['o'] = Math.floor(map['o'] / 2);
    return Math.min(...Object.values(map));
};
    return Math.min(...Object.values(map));
  1. a,b,l,n,o만 카운팅 해서
  2. l과 o는 2로 나눠 몫만 남기고
  3. map 객체의 최소값을 구하면 문자열 balloon의 개수
  • Runtime 60 ms, Memory 41.6 MB
profile
내일도 글쓰기

0개의 댓글