771. Jewels and Stones

232 阅读1分钟

date: 2018/05/11 原文


Question

S集合是自己拥有的宝石,J是宝石的类型,请算出自己拥有几颗商店中的宝石.

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:

Input: J = "z", S = "ZZ"
Output: 0

Solve:

class Solution {
    public int numJewelsInStones(String J, String S) {
        int result = 0;
        char[] have = S.toCharArray();
        HashMap<Character, Integer> map = new HashMap<>();
        for (char char : have) {
            Integer count = map.get(char);
            if (count == null) {
                map.put(char, 1);
            } else {
                map.put(char, count+1);
            }
        }
        char[] item = J.toCharArray();
        for (char char : item) {
            Integer count = map.get(char);
            if (count!=null) {
                result = result + count;
            }
        }
        return result;  
    }
}

Thnking

思路: 把自己拥有的宝石数,放进一个map中,key为宝石的种类,value为拥有的个数。存完后,遍历店铺的,如果店铺里的宝石与map中一致,就将map中的总数取出来,进行相加。