백준

[백준 1181번] 단어정렬 / Set(배열중복제거) / localeCompare() (단어정렬)

mark340 2023. 1. 14. 17:10

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

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

 

let input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n')
const result = [...new Set(input.slice(1))]
.sort((a,b) => a.length-b.length || a.localeCompare(b));

console.log(result.join('\n'))

 

 

localeCompare()

localeCompare 메서드는 참조 문자열이 정렬 순서에서 앞 또는 뒤에 오는지 또는 주어진 문자열과 같은지를 숫자로 반환

referenceStr.localeCompare(compareString[, locales[, options]])

referenceStr이 compareString보다 앞에 있으면 -1, 뒤에 있으면 1, 같으면 0 반환

'a'.localeCompare('b') // -1 , 
'b'.localeCompare('a') // 1
'c'.localeCompare('c') // 0

sort메서드와 조합해서 사용하면 굉장히 유용하고 간단하게 처리할수 있다.

 

 

 

Set

Set 객체는 중복되지 않는 유일한 값들의 집합. Set 객체의 특성은 수학적 집합의 특성과 일치한다. Set 은 수학적 집합을 표현한 자료구조이다. 이를 통해 교집합, 합집합, 차집합, 여집합등을 구현하는 것이 가능하다.

 

Set 객체와 배열의 차이

1. 동일한 값을 중복하여 포함할 수 없다.
2. 요소 순서에 의미가 없다.
3. 인덱스로 요소 접근이 불가능하다.

 

Set 객체 생성

const set = new Set();
console.log(set); // Set(0) {}

const set1 = new Set([1, 2, 3, 3]);
console.log(set1); // Set(3) {1, 2, 3}

const set2 = new Set('hello');
console.log(set2); // Set(4) {"h", "e", "l", "o"}

// Set을 사용한 배열의 중복 요소 제거
const uniq = array => [...new Set(array)];
console.log(uniq([2, 1, 2, 3, 4, 3, 4])); // [2, 1, 3, 4]