https://www.acmicpc.net/problem/20920
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();
}