백준 문제 풀이/백준 (JAVA)
JAVA 백준 1181 단어 정렬 (정렬)
gamja00
2024. 7. 3. 14:24
https://www.acmicpc.net/problem/1181
초기 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < N; i++) {
String word = br.readLine();
if (!arr.contains(word)) {
arr.add(word);
}
}
arr.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() == o2.length()) {
int count = 0;
while (o1.charAt(count) == o2.charAt(count)) {
count++;
}
if (o1.charAt(count) > o2.charAt(count)) {
return o2.charAt(count) - o1.charAt(count);
} else {
return o1.charAt(count) - o2.charAt(count);
}
} else {
return o1.length() - o2.length();
}
}
});
for (String w : arr) {
System.out.println(w);
}
}
}
최종 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < N; i++) {
String word = br.readLine();
if (!arr.contains(word)) {
arr.add(word);
}
}
arr.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() == o2.length()) {
return o1.compareTo(o2);
} else {
return o1.length() - o2.length();
}
}
});
for (String w : arr) {
System.out.println(w);
}
}
}
사실 문자열 비교에서 함수 쓰는 거 생각도 못하고 만들다가... 그래 자바가 얼마나 좋은 언어인데 나를 위한 비교 함수 하나 없을까 싶어서 찾아보니까 compareTo 함수 있길래 고생하다가 바로 함수 써서 풀었다...
앞으로는 메서드 뭐 있나 좀 보고 풀어야겠다...