[leetcode, JS] 49. Group Anagrams

mxxn·2023년 9월 19일
0

leetcode

목록 보기
79/198

문제

문제 링크 : Group Anagrams

풀이

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function(strs) {
    const sortStrs = strs.map(e => {
        return e.split('').sort().join('')
    })
    const mapSortStr = new Map();
    sortStrs.forEach(e => {
        mapSortStr.has(e) ? mapSortStr.set(e, mapSortStr.get(e) + 1) : mapSortStr.set(e, 1)
    })
    const mapKeys = [...mapSortStr.keys()]
    const result = Array.from(Array(mapKeys.length), () => [])
    sortStrs.forEach( (e,i) => {
        result[mapKeys.indexOf(e)].push(strs[i])
    })
    
    return result.sort( (a,b) =>  a.length - b.length)
};
  1. 배열 strs의 string element들을 sort한 값을 만들고
  2. 해당 string들을 Map에 넣어 중복을 걸러내고
  3. Map의 key값과 strs 배열의 element를 비교하여 result를 return
  • Runtime 208 ms, Memory 54.2 MB

다른 풀이

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function(strs) {
    let map = {}

    for(let str of strs) {
        let s = str.split('').sort().join('')

        if(!map[s]) map[s] = []

        map[s].push(str)
    }
    return Object.values(map)
};
  1. Map 개념을 쓰면서 더 간소하게 만든 풀이
  • Runtime 93 ms, Memory 53.7 MB
profile
내일도 글쓰기

0개의 댓글