관리 메뉴

🌲자라나는청년

Q1181 단어 정렬(java) 본문

알고리즘 문제풀이

Q1181 단어 정렬(java)

JihyunLee 2019. 9. 15. 17:23
반응형

 

도움을 받은 곳 : https://bcp0109.tistory.com/5

 

백준 1181번. 단어 정렬 (Java)

문제 링크 : https://www.acmicpc.net/problem/1181 N 개의 단어를 받아서 1. 길이가 짧은 것부터 2. 길이가 같으면 사전 순으로 정렬하여 출력하는 문제입니다. 하지만 문제를 자세히 읽어보면 중복된 단어의 경..

bcp0109.tistory.com

 

나의 코드:

 

버퍼로 입력받기 -> SET으로 넣어 중복 없에주기 -> set을 LIST로 만들어주기 -> compare를 수정하기 -> 출력

 

 

버퍼로 입력받기 : 

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

 

int N = Integer.parseInt(bf.readLine)

 

Set만들고 넣기:

HashSet<String> set = new HashSet<String>();

 

Arraylist 로 변환하기 : 

ArrayList<String> list  = new ArrayList<String>(set);

 

compare 수정하기:

Collections.sort(list, new Comparator<String>{

 public int compare(String v1, String v2){

  // 1 일때 변경된다

  if(v1.length()>v2.length()) return 1;

 else if (v1.length()<v2.lenght()) return -1;

 else{

 return v1.compareTo(v2);

});

 

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
32
33
34
35
import java.util.*;
import java.io.*;
 
 
 
public class Q1181{
    public static void main(String[] args) throws Exception{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        
        int N = Integer.parseInt(bf.readLine());
 
        HashSet<String> set = new HashSet<String>();
 
        for(int i=0; i<N; i++)
            set.add(bf.readLine());
 
        ArrayList<String> list = new ArrayList<String>(set);
 
        Collections.sort(list, new Comparator<String>(){
            public int compare(String v1, String v2){
                if(v1.length()>v2.length())
                    return 1;
                else if(v1.length()<v2.length())
                    return -1;
                else{
                    return v1.compareTo(v2);
                }
            }
        });
 
        for(String s : list){
            System.out.println(s);
        }    
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

반응형

'알고리즘 문제풀이' 카테고리의 다른 글

Q1463 1로 만들기(java)  (0) 2019.09.19
Q11650 좌표정렬하기(java)  (0) 2019.09.15
Q1427 소트인사이드(java)  (0) 2019.09.15
Q1026 보물(java)  (0) 2019.09.15
Q9496 텀프로젝트(시간초과로 실패)  (0) 2019.05.07