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<String, Integer> 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<String, Integer> mapA = new HashMap<String, Integer>();
        HashMap<String, Integer> mapB = new HashMap<String, Integer>();
        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));
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容