Skip to content

Latest commit

 

History

History
40 lines (34 loc) · 892 Bytes

1181.md

File metadata and controls

40 lines (34 loc) · 892 Bytes

단어 정렬

문제

https://www.acmicpc.net/problem/1181

정답

// 구조분해 할당
let [num, ...list] = require("fs")
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "./input.txt")
  .toString()
  .trim()
  .split("\n");

// 중복을 제거하기 위해 set 이용
const uniqueList = Array.from(new Set(list));

console.log(
  uniqueList
    .sort((a, b) => {
      // 길이가 같은 경우 사전순으로 정렬
      if (a.length === b.length) {
        // 다음과 같은 방법으로도 구현이 가능하다.
        // if (a < b) return 1
        // else if (a > b) return 1
        // else return 0
        for (let i = 0; i < a.length; i++) {
          if (a[i] !== b[i]) {
            return a.charCodeAt(i) - b.charCodeAt(i);
          }
        }
      } else {
        return a.length - b.length;
      }
    })
    .join("\n")
);