Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him through his handwriting. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use only whole words available in the magazine. He cannot use substrings or concatenation to create the words he needs.
Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No.
magazine = "attack at dawn" note = "Attack at dawn"
The magazine has all the right words, but there is a case mismatch. The answer is No.
Complete the checkMagazine function in the editor below. It must print Yes if the note can be formed using the magazine, or No.
checkMagazine has the following parameters:
The first line contains two space-separated integers, m and n, the numbers of words in the magazine and the note, respectively.
The second line contains m space-separated strings, each magazine[i].
The third line contains n space-separated strings, each note[i].
6 4
give me one grand today night
give one grand today
Yes
6 5
two times three is not four
two times two is four
No
'two' only occurs once in the magazine.
7 4
ive got a lovely bunch of coconuts
ive got some coconuts
No
Harold's magazine is missing the word some.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.HashMap;
public class Solution {
// Complete the checkMagazine function below.
static void checkMagazine(String[] magazine, String[] note) {
HashMap<String, Integer> hm = new HashMap<>();
int count = 0;
for (String s : magazine)
hm.put(s, hm.getOrDefault(s, 0) + 1);
for (String s : note) {
if (hm.containsKey(s)) {
hm.replace(s, hm.get(s) - 1);
if (hm.get(s) == 0) {
hm.remove(s);
}
count++;
} else {
break;
}
}
if (count == note.length) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
// 그 밑은 생략.
}
잡지단어를 해시맵에 <단어, 개수> 이렇게 집어넣었다.
노트단어가 해시맵에 있다면 개수(Value)를 1개 줄여주고 count를 1 증가시켰으며, 만약 단어의 개수(Value)가 0이 된다면 해당 단어를 제거했다.
해시맵에 없다면 바로 해당 for문을 빠져나왔다.
마지막으로 count가 노트단어 개수와 같다면 Yes를 출력하고, 아니면 No를 출력시켰다.