본문 바로가기

알고리즘/해커랭크

[해커랭크] Sparse Arrays [JAVA]

문제링크: www.hackerrank.com/challenges/sparse-arrays/problem

 

Sparse Arrays | HackerRank

Determine the number of times a string has previously appeared.

www.hackerrank.com

자료구조 학습을 하려는데 자바는 해시관련 함수를 어떻게 쓰는지 파악할 겸 문제를 골랐다.

 

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;


public class Solution {

    // Complete the matchingStrings function below.
    static int[] matchingStrings(String[] strings, String[] queries) {
        int ret[] = new int[queries.length];
        HashMap<String,Integer> hm = new HashMap<String,Integer>();
        for(int i=0;i<strings.length;i++){
            if(!hm.containsKey(strings[i])){
                hm.put(strings[i],1);
            }else{
                hm.put(strings[i],hm.get(strings[i])+1);
            }
        }
        
        for(int i=0;i<queries.length;i++){
            if(hm.containsKey(queries[i])){
                ret[i] = hm.get(queries[i]);
            }else{
                ret[i] = 0;
            }
            
        }
        return ret;
    }
}