카테고리 없음

[LeetCode] - 보석과 돌

zzoming 2023. 11. 16. 16:58

문제) J는 보석이며, S는 갖고 있는 돌이다. S에는 보석이 몇개나 있을까? 대소문자는 구분한다. 

https://leetcode.com/problems/jewels-and-stones/

 

Jewels and Stones - LeetCode

Can you solve this real interview question? Jewels and Stones - You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to kno

leetcode.com


풀이) collections.Counter을 이용하면 쉽게 풀린다. 

import collections 
class Solution(object):
    def numJewelsInStones(self, jewels, stones):
        """
        :type jewels: str
        :type stones: str
        :rtype: int
        """
        freqs = collections.Counter(stones)
        return sum(list(freqs[j] for j in jewels))