백준-Node.js-1181, 단어 정렬

송철진·2023년 2월 27일
0

백준-Node.js

목록 보기
41/69

풀이

const fs = require('fs');
const input = fs.readFileSync("/dev/stdin").toString().trim()
				.split('\n').slice(1)

const solution = input => {
  let len = {}
  let result = ''
  
  input.forEach(el => len[el] = el.length)
  Object.entries(len).sort()
      .sort((a, b) => a[1] - b[1])
      .forEach(el => result += '\n' + el[0])
  
  return result.slice(1)                          
}

console.log(solution(input))

394ms 로 효율이 좋은 편은 아니다.

  1. 중복 단어를 제거하기 위해 임의의 객체에 단어-길이키-값 쌍으로 저장하고

  2. 단어-길이를 요소로 갖는 배열 Object.entries(len) 에 대하여

  • 1) 단어를 기준으로 사전순 정렬하고, .sort()
  • 2) 길이를 기준으로 오름차순 정렬한 뒤, .sort((a, b) => a[1] - b[1])
  • 3) 단어만 뽑아서 반환한다.

다른 풀이

const input = [
  'but', 'i', 'wont', 'hesitate',
  'no', 'more', 'no', 'more', 'it',
  'cannot', 'wait', 'im', 'yours'
]

function solution(words) {
  let wordSet = [...new Set([...words])];
  
  wordSet.sort((a, b) => {
    if (a.length === b.length) {
      if (b > a) return -1;
    }
    return a.length - b.length;
  });
  
  return wordSet.join("\n");
}

console.log(solution(input))
  1. 중복된 단어를 제거하기 위해 Set() 함수를 사용하고
  2. sort()에 정렬 조건을 추가함으로써 불필요하게 각 단어의 길이를 저장하지 않아도 정렬할 수 있다.
profile
검색하고 기록하며 학습하는 백엔드 개발자

0개의 댓글