[leetcode, JS] 1897. Redistribute Characters to Make All Strings Equal

mxxn·2023년 11월 22일
0

leetcode

목록 보기
130/198

문제

문제 링크 : Redistribute Characters to Make All Strings Equal

풀이

/**
 * @param {string[]} words
 * @return {boolean}
 */
var makeEqual = function(words) {
    let charMap = {}
    words.forEach( e => {
        e.split('').forEach(el => {
            charMap[el] ? charMap[el] += 1 : charMap[el] = 1
        })
    })

    for(let count of Object.values(charMap)) {
       if(count % words.length !== 0) return false
    }
    return true
};
  1. 배열 words 내에 있는 word 문자열들에서 쓰이는 알파벳 개수를 담을 charMap 객체를 만들고
  2. charMap에 카운팅 된 개수들이 words의 길이로 나누어 떨어지는지 판별하여 return
  • Runtime 58 ms, Memory 45.75 MB

다른 풀이

/**
 * @param {string[]} words
 * @return {boolean}
 */
var makeEqual = function(words) {
    let map = {};
    for(let word of words){
        for(let char of word){
            map[char] ? map[char]++ : map[char] = 1;
        }
    }
    for(let num of Object.values(map)){
        if(num % words.length !== 0) return false;
    }
    return true;
};
  1. 같은 방식의 풀이
  • Runtime 60 ms, Memory 44.92 MB
profile
내일도 글쓰기

0개의 댓글