본문 바로가기

Study/Coding Test

[baekjoon] 단어 정렬(JavaScript)

📘 오늘의 코딩테스트 - 단어 정렬(JavaScript)

🔢 문제 번호: 1181번

🔗 문제 링크: 백준 - 단어 정렬

 

 

 

 

🧠 문제 요약

  • 알파벳 소문자로 이루어진 N개의 단어를 특정 조건에 따라 정렬하는 문제
  • 정렬 조건:
    1. 길이가 짧은 것 부터
    2. 길이가 같으면 사전 순으로 단, 중복된 단어는 하나만 남기고 제거해야 한다
  • 입력: 첫째 줄에 단어의 개수 N (1 ≤ N ≤ 20,000)
            둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 주어짐 (길이 ≤ 50)
  • 출력: 조건에 따라 정렬하여 단어들을 한 줄에 하나씩 출력

 

 

 

✅ 실행 예시 및 결과

입력:
13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours

출력:
i
im
it
no
but
more
wait
wont
yours
cannot
hesitate

 

 

 

✍️ 내 풀이

  • Set을 사용하여 중복제거(new Set() 생성자 사용)
  • Arrya.from()으로 Set을 배열로 변환
  • sort() 메서드로 길이순 → 사전순 정렬
  • join('\n')으로 출력 행태 맞춤

 

 

 

💻 내가 푼 코드

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

const N = parseInt(input[0]);
const words = Array.from(new Set(input.slice(1)));
const sortWords = words.sort((a, b) => {
  if (a.length !== b.length) {
    return a.length - b.length;
  } else {
    return a.localeCompare(b);
  }
});

console.log(sortWords.join("\n"));

 

 

 

📎 남이 푼 코드

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

const n = +input[0];
const words = [...new Set(input.slice(1))];
words.sort((a, b) => a.length - b.length || a.localeCompare(b));

console.log(words.join('\n'));
  • 스프레드 연산자 [...new Set()]를 사용해 더 간결하게 중복 제거
  • || 연산자를 활용해 조건부 정렬을 한 줄로 표현
  • +input[0] 단항 연산자로 문자열을 숫자로 변환

 

 

 

🔍 회고 & 배운 점

  • Set 자료구조의 중복 제거를 처음 써봤다!!
  • localeCompare() 메서드로 사전 순 정렬하는 법을 알았다!!
  • 처음에 통과를 못 했던 이유가 처음 input 변수에 trim()을 안 넣어서!! 이제부터는 계속 넣는 걸루!!
반응형