Source : https://www.hackerrank.com/challenges/ctci-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
.
For example, the note is "Attack at dawn". The magazine contains only "attack at dawn". The magazine has all the right words, but there's a case mismatch. The answer is .
Function Description
Complete the checkMagazine function in the editor below. It must print if the note can be formed using the magazine, or .
checkMagazine has the following parameters:
- magazine: an array of strings, each a word in the magazine
- note: an array of strings, each a word in the ransom note
Input Format
The first line contains two space-separated integers, and , the numbers of words in the and the ..
The second line contains space-separated strings, each .
The third line contains space-separated strings, each .
Constraints
- .
- Each word consists of English alphabetic letters (i.e., to and to ).
Output Format
Print Yes
if he can use the magazine to create an untraceable replica of his ransom note. Otherwise, print No
.
Sample Input 0
6 4give me one grand today nightgive one grand today
Sample Output 0
Yes
Sample Input 1
6 5two times three is not fourtwo times two is four
Sample Output 1
No
Explanation 1
'two' only occurs once in the magazine.
Sample Input 2
7 4ive got a lovely bunch of coconutsive got some coconuts
Sample Output 2
No
Explanation 2
Harold's magazine is missing the word .
Source : https://www.hackerrank.com/challenges/ctci-ransom-note
Solution
// Karthikalapati.blogspot.com | |
/* Determines if ransom letter can be made from magazine */ | |
public static void checkMagazine(String[] magazine, String[] ransom) { | |
HashMap<String, Integer> usableWords = makeMap(magazine); | |
for (int i = 0; i < ransom.length; i++) { | |
if (usableWords.containsKey(ransom[i]) && usableWords.get(ransom[i]) > 0) { | |
usableWords.merge(ransom[i], -1, Integer::sum); // uses the word | |
} else { | |
System.out.println("No"); | |
return; | |
} | |
} | |
System.out.println("Yes"); | |
} | |
/* Creates and returns a HashMap out of an array of Strings */ | |
private static HashMap<String, Integer> makeMap(String[] words) { | |
HashMap<String, Integer> map = new HashMap(); | |
for (int i = 0; i < words.length; i++) { | |
map.merge(words[i], 1, Integer::sum); | |
} | |
return map; | |
} |
No comments:
Post a Comment