백준 1181 JS

이진우·2025년 7월 29일
0

알고리즘문제

목록 보기
6/7

문제 링크

1181 단어정렬

해결 과정

배열에 중복된 단어를 먼저 제거하기(방법 2개)
set 사용

let arr = [...new Set(input)];

includes 메서드로 입력받은 배열 검증

let noDuplication = [];
for (let i of input) {
  if (
    !noDuplication.includes(i)) {
    noDuplication.push(i);
  }
}

저장된 단어 정렬하기
-> sort() 사용하기

noDuplication.sort((a, b) => {
  return a.length === b.length
    ? a.charCodeAt(0) - b.charCodeAt(0)
    : a.length - b.length;
});


it와 im의 순서가 안맞음;;


localeCompare() 메서드 사용

arr.sort((a, b) => a.length - b.length || a.localeCompare(b));


성공~

해결

const fs = require("fs");
let [num, ...input] = fs.readFileSync("ex.txt").toString().trim().split("\n");

let arr = [...new Set(input)];

arr.sort((a, b) => a.length - b.length || a.localeCompare(b));
console.log(arr.join("\n"));
profile
츄라이츄라이

0개의 댓글