[백준1181_자바스크립트(javascript)] - 단어 정렬

경이·2024년 6월 2일

𝑩𝑶𝑱 (𝒋𝒔)

목록 보기
53/325

🔴 문제

단어 정렬


🟡 Sol

const fs = require('fs');
const path = process.platform === 'linux' ? '/dev/stdin' : 'Wiki\\input.txt';
const [, ...inputs] = fs.readFileSync(path).toString().trim().split('\n');
const words = Array.from(new Set(inputs));

words.sort((a, b) => {
  if (a.length === b.length) return a > b ? 1 : -1;
  else return a.length - b.length;
});

const answer = words.reduce((pre, cur) => pre + '\n' + cur);
console.log(answer);

🟢 풀이

같은단어가 여러번 나올 수 있으니 중복 제거해준 단어들을 정렬해준다.
만약 두 단어의 길이가 같다면 그냥 단어의 크기비교를 해주면된다. js의 문자열 크기비교는 사전 비교이다.
만약 두 단어의 길이가 다르다면 짧은애를 먼저 오도록 해준다.


🔵 Ref

profile
록타르오가르

0개의 댓글