문제
알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
- 길이가 짧은 것부터
- 길이가 같으면 사전 순으로
단, 중복된 단어는 하나만 남기고 제거해야 한다.
입력
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
출력
조건에 따라 정렬하여 단어들을 출력한다.
예제 입력 1
13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours
예제 출력 1
i
im
it
no
but
more
wait
wont
yours
cannot
hesitate
Comparable 가져와서 좀 편하게 하려다가 난리남
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
public class BOJ_1181 {
static class Word implements Comparable<Word>{
String word;
public Word(String word) {
this.word = word;
}
void printOut() {
System.out.printf("%s ", word);
}
@Override
public int compareTo(Word o) {
if(this.word.length() != o.word.length()) { // 길이 먼저 비교함
if(this.word.length() > o.word.length()) return 1;
return -1;
}else {
return this.word.compareTo(o.word);
}
}
@Override
public boolean equals(Object o) {
Word no = (Word) o;
return this.word.equals(no.word);
}
@Override
public int hashCode() {
return Objects.hash(word);
}
}
static HashSet<Word> words;
static int loop;
public static void main(String[] args) {
words = new HashSet<Word>();
Scanner sc = new Scanner(System.in);
loop = sc.nextInt();
for(int i = 0; i<loop; i++) {
words.add(new Word(sc.next()));
}
ArrayList<Word> list = new ArrayList<>(words);
Collections.sort(list);
for(Word s : list) {
System.out.println(s.word);
}
}
}
Word가 String으로만 이루어져 있긴 하지만 어쨌든 객체이기 때문에
equals()와 hashCode()를 Override해야 HashSet에서 중복값을 걸러낼 수 있다.
허허 .... 왜 그랬지
'2024-?학기 ??? > Solving' 카테고리의 다른 글
BOJ 7785_회사에 있는 사람 (0) | 2024.08.21 |
---|---|
BOJ 10814_나이순 정렬 (0) | 2024.08.20 |
BOJ 2840_행운의 바퀴 (0) | 2024.08.19 |
BOJ 10250_ACM 호텔 (0) | 2024.08.19 |
BOJ 11005_진법 변환 2 (0) | 2024.06.21 |
댓글