Leetcode 771) Jewels and Stones

image

My Solution

class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        //initialize the map
        Map<Character, Integer> m = new HashMap<>();
        char[] stoneChar = stones.toCharArray();
        for(char c : stoneChar){
            if(m.containsKey(c)){
                m.put(c, m.get(c)+1);      
            }else{
                m.put(c,1);
            }
        }
        int cnt =0;
        for(int i =0;i<jewels.length();i++){
            char cur = jewels.charAt(i);
            if(m.containsKey(cur)){
                cnt+=m.get(cur);
            }
        }
        return cnt;
    }
}

Other Solution

class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        int unique = 0;
        for (int i = 0; i < jewels.length(); i++) {
            for (int j = 0; j < stones.length(); j++) {
                if(jewels.charAt(i) == stones.charAt(j)) {
                    unique++;
                }
            }
        }
        return unique;
    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2