반응형
1). 문제 : www.hackerrank.com/challenges/ctci-ransom-note/
Hash Tables: Ransom Note | HackerRank
Given two sets of dictionaries, tell if one of them is a subset of the other.
www.hackerrank.com
2). 풀이 :
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the checkMagazine function below.
static void checkMagazine(String[] magazine, String[] note) {
HashMap<String,Integer> a = new HashMap<String,Integer>();
for(int i=0; i<magazine.length; i++){
if(!a.containsKey(magazine[i])) {
a.put(magazine[i],1);
}else {
//있다면 누적
a.put(magazine[i],a.get(magazine[i])+1);
}
}
for(int i=0; i<note.length; i++){
//있는지 없는지 부터 체크
if(!a.containsKey(note[i])){
System.out.print("No");
return;
}else{
if(a.get(note[i])>0){
//한개씩 빼기
a.put(note[i],a.get(note[i])-1);
}else{
System.out.print("No");
return;
}
}
}
System.out.print("Yes");
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String[] mn = scanner.nextLine().split(" ");
int m = Integer.parseInt(mn[0]);
int n = Integer.parseInt(mn[1]);
String[] magazine = new String[m];
String[] magazineItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < m; i++) {
String magazineItem = magazineItems[i];
magazine[i] = magazineItem;
}
String[] note = new String[n];
String[] noteItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
String noteItem = noteItems[i];
note[i] = noteItem;
}
checkMagazine(magazine, note);
scanner.close();
}
}
과정 1 : 잡지에 있는 단어가 중복 될 수도 있기 때문에, map을 사용하여 value로 중복 갯수를 체크하였다.
과정 2 : note에 있는 단어 하나씩 map에 있는지 확인 하며, 없을땐 No를 출력하고 메서드를 마친다.
과정 3 : note에 있는 단어 하나씩 map에 있는지 확인 하며, 있을땐 갯수를 확인하는 로직을 추가한다.
=> 잡지에 있는 단어 모두를 사용했을 수도 있기 때문에.
과정 4 : map에 사용할 수 있는 note에서 뽑아온 단어 갯수가 0초과일경우 (있을경우) 사용한것 처럼 갯수를 -1 해준다.
과정 5 : 갯수가 0일 경우 사용할 수 있는 단어가 없기때문에 No 출력 후 메서드 마침
반응형
'Java > Algorithm' 카테고리의 다른 글
[Java-Algorithm] HackerRank Java - Sherlock and Anagrams 풀이 (0) | 2021.01.29 |
---|---|
[Java-Algorithm] HackerRank Java - Two Strings 풀이 (0) | 2021.01.29 |
[Java-Algorithm] HackerRank Java - Array Manipulation -누적합풀이 (0) | 2021.01.27 |
[Java-Algorithm] HackerRank Java - Mark and Toys 풀이 (0) | 2021.01.27 |
[Java-Algorithm] HackerRank Java Minimum Swaps 2 풀이 (0) | 2021.01.26 |