티스토리 뷰

728x90

https://www.acmicpc.net/problem/1181

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1≤N≤20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

[정렬] Java

오랜만에 자바로 푸니까 다 까먹음 진짜

반성하면서 앞으로 자바로 풀겠습니다..

 

문제가 딱 생긴게 자바로 풀면 딱이라 시도해봤는데

그건 맞는데 암튼

 

1. 길이로 정렬 -> Collections.sort사용 comparator써서 a.length()-b.length() 반환

2. 길이가 같으면 사전순으로 정렬 -> Collections.sort comparator에서 a.compareto(b) 사용

3. 중복없이 출력 -> HashSet 사용 (처음 써봄)

 

소스코드

 

import java.util.*;

public class CharSotring {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());

        //중복없이 입력받음
        HashSet<String> strSet = new HashSet<>();
        String str;
        for(int i = 0 ; i < n ; i++){
            str = in.nextLine();
            strSet.add(str);
        }
        //정렬 1.길이 2. 길이같으면 사전순
        ArrayList<String> arrList = new ArrayList<>(strSet);
        Collections.sort(arrList, (a,b)->{if(a.length() == b.length()) return a.compareTo(b); else return a.length()-b.length();});
        //출력
        for(String s : arrList)
            System.out.println(s);
    }
}
728x90
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함