728x90
문제
알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
- 길이가 짧은 것부터
- 길이가 같으면 사전 순으로
입력
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
출력
조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러 번 입력된 경우에는 한 번씩만 출력한다.
Comparator를 이용하여 String을 비교하는 compareTo() 메소드를 override 하였다.
먼저 길이를 비교하고, 길이가 같으면 그때 사전순으로 (기존 String 비교 방식) 비교하도록 구현하였다.
또한 출력할 때 같은 단어는 한 번만 출력하도록 하였다. (처음부터 Map을 쓰면 더 간단할듯!)
package BOJ0726;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class BOJ_1181_WordSort {
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
ArrayList<String> arr = new ArrayList<>();
for (int i = 0; i < N; i++) {
arr.add(sc.next());
}
Collections.sort(arr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() != o2.length()) {
return o1.length() - o2.length();
} else {
return o1.compareTo(o2);
}
}
});
for (int i = 0; i < arr.size(); i++) {
if (i == 0 || !arr.get(i - 1).equals(arr.get(i))) {
System.out.println(arr.get(i));
}
}
}
}
728x90
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 2839 - 설탕 배달 (자바/Java) (0) | 2022.07.26 |
---|---|
[백준] 1065 - 한수 (자바/Java) (0) | 2022.07.26 |
[백준] 2869 - 달팽이는 올라가고 싶다 (자바/Java) (0) | 2022.07.26 |
[백준] 1316 - 그룹 단어 체커 (자바/Java) (0) | 2022.07.26 |
[백준] 10989 - 수 정렬하기 3 (자바/Java) : 계수 정렬(Counting Sort) (0) | 2022.07.26 |