2021.01.13 연습

 

  • 사용언어 : java

 


class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        
        int count = 0;
        
        Map<Character, Character> map = new HashMap<>();
        for (char i : jewels.toCharArray()) {
            map.put(i, i);
        }
        
        for (char i : stones.toCharArray()) {
            if (map.containsKey(i)) count++;
        }
        
        return count;
        
    }
}

Runtime: 1 ms, faster than 71.58% of Java online submissions for Jewels and Stones. Memory Usage: 37.8 MB, less than 19.41% of Java online submissions for Jewels and Stones.


  • 다른 코드 참고

class Solution {
    public int numJewelsInStones(String J, String S) {
        
        // creating a hash set of characters
        HashSet<Character> set=new HashSet<Character>();
        
        // if the length of the string is 0, then there could be no duplicates
        if (J.length() < 1){
            return 0;
        }
        
        // inserting J into the hash set, char by char
        for (int i = 0; i < J.length(); i++) {
            set.add(J.charAt(i));
        }
        // creating a duplicate integer value
        int dup = 0;
        
        // iterate through the string S and see if the char is contained in the set 
        for (int i = 0; i < S.length(); i++) {
            if (set.contains(S.charAt(i)) == true){
                dup += 1;
            }
        }
        // return dup value
        return dup;
    } 
}