
알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
- 길이가 짧은 것부터
- 길이가 같으면 사전 순으로
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러 번 입력된 경우에는 한 번씩만 출력한다.
주어지는 문자열의 길이에 따라 정렬하여 출력하는 문제이다. 유의해야하는 점은 같은 단어가 여러 번 입력된 경우 한번씩만 출력한다는 점이다.
문자열과 문자열의 길이를 저장할 수 있는 클래스를 선언한 뒤 길이에 따른 compareTo()함수를 정의한다. 이후 N개 만큼 입력을 받아서 ArrayList에 저장하면 되는데, 저장하긱 전에 이미 리스트에 저장되어 있는지 확인하는 과정을 거쳐야 한다.
최종적으로 Collections.sort()를 사용하여 정렬한 뒤 출력하면 된다.
import java.util.*;
class Word implements Comparable<Word> {
private String word;
private int len;
public Word(String word, int len) {
this.word = word;
this.len = len;
}
public String getWord() {
return word;
}
@Override
public int compareTo(Word o) {
if (this.len == o.len) {
return word.compareTo(o.word);
}
return Integer.compare(this.len, o.len);
}
}
public class Main {
public static ArrayList<Word> words = new ArrayList<Word>();
public static boolean check(String word) {
for (int i = 0; i < words.size(); i++) {
if (words.get(i).getWord().equals(word)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++) {
String word = sc.nextLine();
int len = word.length();
if (check(word) == false) {
words.add(new Word(word, len));
}
}
Collections.sort(words);
for (Word word : words) {
System.out.println(word.getWord());
}
}
}