Cracking the Interview - hashmap

The Using of HashMap

A kidnapper wrote a ransom note but is worried it will be traced back to him. 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 whole words available in the magazine, meaning he cannot use substrings or concatenation to create the words he needs.

Here is my solution to this problem in Java
https://www.hackerrank.com/challenges/ctci-ransom-note

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {   
    public static void fillmap(HashMap map, String[] value ){
        if(value == null) return;
        for(int i = 0; i < value.length; i++){
            if(!map.containsKey(value[i]))
                map.put(value[i],1);
            else {
               Integer current = map.get(value[i]);
                if (current == null) current = 0;
                map.put(value[i], current+1);
            }
        }
    }    
    public static String Answer(String[] magazine, String[] ransom){
        HashMap mapA = new HashMap();
        HashMap mapB = new HashMap();
        if(magazine.length < ransom.length)
            return "No";  
        //input magazine into hashmap
        fillmap(mapA, magazine);
        // input ransom into hashmap
       fillmap(mapB, ransom);
        for(String str: mapB.keySet()){
            if(!mapA.containsKey(str))
                return "No";
            Integer countA = mapA.get(str);
            Integer countB = mapB.get(str);
            if(countB > countA)
                return "No";

        }
        return "Yes";
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        int n = in.nextInt();
        String magazine[] = new String[m];
        for(int magazine_i=0; magazine_i < m; magazine_i++){
            magazine[magazine_i] = in.next();
        }
        String ransom[] = new String[n];
        for(int ransom_i=0; ransom_i < n; ransom_i++){
            ransom[ransom_i] = in.next();
        }
        System.out.println(Answer(magazine, ransom));
    }
}

你可能感兴趣的:(Cracking the Interview - hashmap)