새소식

Algorithm/BOJ

(JAVA) [BOJ]백준 20920번, 영단어 암기는 외로워

  • -
728x90

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

 

20920번: 영단어 암기는 괴로워

첫째 줄에는 영어 지문에 나오는 단어의 개수 $N$과 외울 단어의 길이 기준이 되는 $M$이 공백으로 구분되어 주어진다. ($1 \leq N \leq 100\,000$, $1 \leq M \leq 10$) 둘째 줄부터 $N+1$번째 줄까지 외울 단

www.acmicpc.net

20920, 영단어 암기는 어려워

[ 난이도 : 실버 3 ]

이번 문제는 HashMap 과 List 를 사용하여 풀이해보겠다.

 

Process

input

: 단어의 수 N과 길이의 기준 M 이주어진다. M보다 길이가 같거나 긴 단어들을 HashMap 에 넣어주겠다.

static int N, M;
static String str;
static ArrayList<String> List;
static HashMap<String, Integer> words;

static void input() 
{
    words = new HashMap<>();
    N = scan.nextInt(); M = scan.nextInt();
    while(N-- > 0)
    {
        str = scan.next();
        if(str.length() < M) continue;

        words.put(str, words.getOrDefault(str, 0)+1);
    }
}

 

구현

: 위에서 선언한 words 를 리스트로 재선언해준다. 이는 정렬을 진행하기 위해서이다.

HashMap 을 List 로 변환하는 코드는 종종 사용할 것 같아 기억해두면 좋을 것 같다.

List<String> word = words.keySet().stream().collect(Collectors.toList());

 

선언한 리스트를 아래와 같이 정렬해주면 된다.

static void pro() 
{   
    // HashMap to List 변환
    List<String> word = words.keySet().stream().collect(Collectors.toList());

    word.sort((o1, o2) -> {
        int c1 = words.get(o1);
        int c2 = words.get(o2);

        if(c1 == c2)
        {
            if(o1.length() == o2.length()) return o1.compareTo(o2);

            return o2.length() - o1.length();
        }

        return c2 - c1;
    });

    for(int i=0; i<word.size(); i++) sb.append(word.get(i)+"\n");

    System.out.println(sb);
}

 

전체 코드

: 어렵지는 않은 구현문제인데 정렬하는 과정이 조금 어려웠었다.

이번에 사용한 코드들을 잘 기억해두자!

static int N, M;
static String str;
static ArrayList<String> List;
static HashMap<String, Integer> words;

static void input() 
{
    words = new HashMap<>();
    N = scan.nextInt(); M = scan.nextInt();
    while(N-- > 0)
    {
        str = scan.next();
        if(str.length() < M) continue;

        words.put(str, words.getOrDefault(str, 0)+1);
    }
}

static void pro() 
{   
    // HashMap to List 변환
    List<String> word = words.keySet().stream().collect(Collectors.toList());

    word.sort((o1, o2) -> {
        int c1 = words.get(o1);
        int c2 = words.get(o2);

        if(c1 == c2)
        {
            if(o1.length() == o2.length()) return o1.compareTo(o2);

            return o2.length() - o1.length();
        }

        return c2 - c1;
    });

    for(int i=0; i<word.size(); i++) sb.append(word.get(i)+"\n");

    System.out.println(sb);
}

public static void main(String[] args) 
{
    input();
    pro();	
}

 

 

728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.