코딩테스트-알고리즘/백준 BOJ

[백준 BOJ/Silver V] 1181번 : 단어 정렬

닉네임생각즁 2024. 1. 14. 20:00

 

 

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

 

1181번: 단어 정렬

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

www.acmicpc.net

 

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        Map<String, Integer> map = new HashMap<>();
        for(int i=0; i<N; i++) {
            String word = sc.next();
            map.put(word, word.length());
        }

        List<Map.Entry<String, Integer>> entryList = new LinkedList<>(map.entrySet());
        entryList.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                int comparision = o1.getValue() - o2.getValue();
                return comparision == 0 ? o1.getKey().compareTo(o2.getKey()) : comparision;
            }
        });

        for(int i=0; i< entryList.size(); i++) {
            System.out.println(entryList.get(i).getKey());
        }

    }
}

 

Map 진짜 좋은거같다 중복된건 알아서 무시해주니까 같으면 넣지마라고 조건문을 쓸 필요도 없음👍👍

value 기준으로 정렬하기 위해서는 LinkedList에 넣어준 후 뽑아주면 됐고, compare에 어떻게 작성해주냐에 따라 정렬 후 또 정렬을 해줄 수도 있었다 이건 다양하게 이용할 수 있을거같아서 꼭 기억해두려고한다

 

배운 내용은 아래에 정리했다

https://fruits2lim.tistory.com/entry/%EC%98%A4%EB%8A%98%EC%9D%98-%EC%9E%90%EB%B0%94-%EB%AC%B8%EB%B2%95-HashMap-%EC%A0%95%EB%A0%AC-2

 

[오늘의 자바 문법] HashMap 정렬-2

HashMap value 기준 정렬 - key 값 기준 오름차순 정렬은 TreeMap으로 가능 - value 값 기준 정렬은 다른걸 이용해줘야함 1) List entryList = new LinkedList(map.entrySet()); entryList.sort(Map.Entry.comparingByValue()); for(Map.Ent

fruits2lim.tistory.com

 

 

 

+

새롭게 해본 방법

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		String[] word = new String[N];
		for(int i=0; i<N; i++) {
			word[i] = sc.next();
		}
		
		Arrays.sort(word, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				if (o1.length() != o2.length()) 
					return o1.length() - o2.length();
				else return o1.compareTo(o2);
			}
		});
		
		String[] wordResult = Arrays.stream(word).distinct().toArray(String[]::new);
		
		for(String s : wordResult) {
			System.out.println(s);
		}
	}
}