LeetCode 771. Jewels and Stones (Java)

Kim Yongbin·2024년 4월 21일
post-thumbnail

문제

Jewels and Stones - LeetCode

Code

class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        int answer = 0;
        Map<Character, Integer> stoneCountMap = new HashMap<>();

        for (char stone: stones.toCharArray()){
            int count = stoneCountMap.getOrDefault(stone, 0);
            stoneCountMap.put(stone, count + 1);
        }

        for (char jewel: jewels.toCharArray()){
            answer += stoneCountMap.getOrDefault(jewel, 0);
        }

        return answer;
    }
}

먼저 주어진 Stones에 대하여 각 종류별 개수를 세어 HashMap에 매핑시켰다. 이후 Jewels의 문자마다 몇개씩 있는지 찾아 더해주었다.

profile
반박 시 여러분의 말이 맞습니다.

0개의 댓글