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));
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容