https://www.acmicpc.net/problem/1181
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Map<String, Integer> map = new HashMap<>();
for(int i=0; i<N; i++) {
String word = sc.next();
map.put(word, word.length());
}
List<Map.Entry<String, Integer>> entryList = new LinkedList<>(map.entrySet());
entryList.sort(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
int comparision = o1.getValue() - o2.getValue();
return comparision == 0 ? o1.getKey().compareTo(o2.getKey()) : comparision;
}
});
for(int i=0; i< entryList.size(); i++) {
System.out.println(entryList.get(i).getKey());
}
}
}
Map 진짜 좋은거같다 중복된건 알아서 무시해주니까 같으면 넣지마라고 조건문을 쓸 필요도 없음👍👍
value 기준으로 정렬하기 위해서는 LinkedList에 넣어준 후 뽑아주면 됐고, compare에 어떻게 작성해주냐에 따라 정렬 후 또 정렬을 해줄 수도 있었다 이건 다양하게 이용할 수 있을거같아서 꼭 기억해두려고한다
배운 내용은 아래에 정리했다
+
새롭게 해본 방법
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String[] word = new String[N];
for(int i=0; i<N; i++) {
word[i] = sc.next();
}
Arrays.sort(word, 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);
}
});
String[] wordResult = Arrays.stream(word).distinct().toArray(String[]::new);
for(String s : wordResult) {
System.out.println(s);
}
}
}
'코딩테스트-알고리즘 > 백준 BOJ' 카테고리의 다른 글
[백준 BOJ/Silver V] 11651번 : 좌표 정렬하기 2 (0) | 2024.01.17 |
---|---|
[백준 BOJ/Silver V] 11650번 : 좌표 정렬하기 (1) | 2024.01.15 |
[백준 BOJ/Bronze I] 1157번 : 단어 공부 (0) | 2024.01.14 |
[백준 BOJ/Silver IV] 11652번 : 카드 (4) | 2024.01.13 |
[백준 BOJ/Silver I] 금민수의 개수 (2) | 2024.01.09 |