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 know how many of the stones you have are also jewels.
- Letters are case sensitive, so "a" is considered a different type of stone from "A"
=> 보석과 원석이 문자열로 입력값이 주어지며, 원석중 보석의 개수를 파악하여 반환하는데, 문자는 대, 소문자를 구분하므로 "aA"라면 a, A는 다른 보석으로 간주됩니다.
Solution
import collections
preJewels = "aA"
preStones = "aAAbbbb"
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
res = collections.Counter(stones)
return sum([res[k] for k in jewels])
sol = Solution()
print(sol.numJewelsInStones(preJewels, preStones))
📌 코드 풀이
- collections의 Counter를 이용하여 같은 원석의 개수를 카운팅 한다.
- 리스트에서 for문을 이용하여 jewels의 문자들을 key로 이용하여 1번에서 만든 카운터 딕셔너리의 키값으로 이용한다.
- 리스트에 원석에서 보석에 해당하는 개수가 들어있기 때문에 sum()을 이용해 요소의 합을 반환하면 된다.
leetcode
https://leetcode.com/problems/jewels-and-stones/