https://www.acmicpc.net/problem/1181
문자열
정렬
정렬과 문자열을 동시에 이용하는 풀이다.
Array의 sort에서 두번째 인자로 정렬의 조건을 직접 설정할 수 있다.
양수이면 두 비교대상의 자리를 바꾸고 음수이거나 0이면 그대로 유지한다.
그래서 보통 아래의 예시처럼 사용한다.
list.sort((o1, o2) -> {
// 두 비교대상의 길이를 빼서 음수면 왼쪽이 크니까 이 경우는 오름차순이 된다.
return o1.length() - o2.length();
// 두 비교대상중 왼쪽이 크면 -1을 리턴하므로 내림차순이 된다.
if (o1.length() > o2.length()) {
return -1;
}
});
정렬할때 필수적으로 사용하기 때문에 꼭 기억해둔다.
// distinct를 이용하여 중복을 제거하고 collect를 이용하여 다시 list로 변환해준다.
list.stream().distinct().collect(Collectors.toList());
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
class Main {
public void solution(String[] s) {
int answer = 0;
ArrayList<String> list = new ArrayList<>(Arrays.asList(s));
list.sort((o1, o2) -> {
if (o1.length() == o2.length()) {
return o1.compareTo(o2);
}
return o1.length() - o2.length();
});
List<String> listDistinct = list.stream().distinct().collect(Collectors.toList());
for (String x : listDistinct) {
System.out.println(x);
}
}
public static void main(String[] args) throws IOException {
Main solution = new Main();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] s = new String[n];
for (int i = 0; i < n; i++) {
s[i] = br.readLine();
}
solution.solution(s);
}
}