https://www.acmicpc.net/problem/1181
// 길이로 비교하고, 기본 compareTo 비교.
// 프로덕션코드
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Yun_1181 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfWord = scanner.nextInt();
scanner.nextLine();
String[] words = new String[numberOfWord];
for (int i = 0; i < numberOfWord; i++) {
words[i] = scanner.nextLine();
}
Arrays.sort(words, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() != o2.length()) {
return o1.length() - o2.length();
}
return o1.compareTo(o2);
}
});
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
}
}
// 실패! 중복 제거를 안해줬네. 배열보다 어레이리스트가 좋겠다.
// 프로덕션코드
import java.util.*;
public class Yun_1181 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfWord = scanner.nextInt();
scanner.nextLine();
List<String> words = new ArrayList<>();
for (int i = 0; i < numberOfWord; i++) {
String newWord = scanner.nextLine();
if (!words.contains(newWord)) {
words.add(newWord);
}
}
Collections.sort(words, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() != o2.length()) {
return o1.length() - o2.length();
}
return o1.compareTo(o2);
}
});
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i));
}
}
}
// 성공! 리팩토링하고 마무리
// 프로덕션코드
import java.util.*;
public class Yun_1181 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfWord = scanner.nextInt();
scanner.nextLine();
List<String> words = new ArrayList<>();
setWords(scanner, numberOfWord, words);
sorting(words);
printWords(words);
}
private static void sorting(List<String> words) {
Collections.sort(words, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() != o2.length()) {
return o1.length() - o2.length();
}
return o1.compareTo(o2);
}
});
}
private static void printWords(List<String> words) {
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i));
}
}
private static void setWords(Scanner scanner, int numberOfWord, List<String> words) {
for (int i = 0; i < numberOfWord; i++) {
String newWord = scanner.nextLine();
if (!words.contains(newWord)) {
words.add(newWord);
}
}
}
}
'코딩테스트연습 > 백준' 카테고리의 다른 글
[백준 - JAVA] 2775번 부녀회장이 될테야 (0) | 2021.12.18 |
---|---|
[백준 - JAVA] 2292번 벌집 (0) | 2021.12.18 |
[백준 - JAVA] 10814번 나이순 정렬 (0) | 2021.12.15 |
[백준 - JAVA] 11650번 좌표 정렬하기 (0) | 2021.12.15 |
[백준 - JAVA] 10989 수 정렬하기 3 (0) | 2021.12.14 |