백준 4358번 생태학

이상민·2023년 10월 20일
0

알고리즘

목록 보기
78/128
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Ecology {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        HashMap<String,Integer> map = new HashMap<>();
        int cnt = 0;
        while (true){
            String str = br.readLine();

            if(str==null||str.length()==0){
                break;
            }
            cnt++;
            map.put(str,map.getOrDefault(str,0)+1);
        }
        List<String> list = new ArrayList<>(map.keySet());
        Collections.sort(list);

        for(Object key: list){
            int count = map.get(key);
            double per =  (count*100.0)/cnt ;
            System.out.printf("%s %.4f\n",key,per);
        }

    }
}

풀이방법

map.put(str,map.getOrDefault(str,0)+1);
이 코드가 풀이의 핵심이다.

  1. 중복제거하면서, 몇번 입력되었는지 확인한다.
  2. 리스트에 키를 담아서 정렬한다.
  3. 리스트를 돌면서 조건에 따라 출력한다.
profile
개린이

0개의 댓글