Hash Tables: Ransom Note
🔗 문제 링크
❔ 문제 설명
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.
Example
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.
Function Description
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:
- string magazine[m]: the words in the magazine
- string note[n]: the words in the ransom note
Prints
- string: either Yes or No, no return value is expected
Input Format
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 space-separated strings, each magazine[i].
The third line contains space-separated strings, each note[i].
⚠️ 제한사항
-
-
-
Each word consists of English alphabetic letters (i.e., a to z and A to Z).
💡 풀이 (언어 : Java)
Hashtable을 사용해서 풀었다. 키값은 대소문자를 구별하기 때문에 별도의 대소문자 처리는 필요가 없었다. 디테일하게 고려한 점은 Hashtable에 value로 단어 수를 카운팅해서 넣어주었다. 같은 글자가 연속으로 필요할 때는 잡지에는 하나만 있는데, value로 단어 수를 차감해주지 않으면 note에서 여러번 등장해도 계속 사용가능한 것으로 판별되는 것을 고려해서 작성했다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class Main {
private static String checkMagazine(String[] magazine, String[] note) {
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
for (String word : magazine) {
if (!ht.containsKey(word)) {
ht.put(word, 1);
} else {
ht.replace(word, ht.get(word)+1);
}
}
for (String word : note) {
Integer num = ht.get(word);
if (num == null || num < 1) {
return "No";
} else {
ht.replace(word, num-1);
}
}
return "Yes";
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
String[] magazine = br.readLine().split(" ");
String[] note = br.readLine().split(" ");
System.out.println(checkMagazine(magazine, note));
br.close();
}
}
Author And Source
이 문제에 관하여(Hash Tables: Ransom Note), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@shiningcastle/Hash-Tables-Ransom-Note저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)