Category | ps/자료구조 |
---|---|
Tag | 자료구조 |
Tags | hash map |
난이도 | ★ |
발행 여부 | |
사이트 | Leet code |
실수 유형 | |
이해 | 완벽히 이해 |
최종 편집 일시 | |
푼 날짜 |
문제 해설 및 주의사항
원문
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"
.
Example 1:
Input: jewels = "aA", stones = "aAAbbbb" Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ" Output: 0
번역 및 주의사항
jewels
: 무엇이 보석인지 나타낸다.
stones
: 내가 가지고 있는 돌을 나타낸다.
stones
안에 보석이 몇 개 있는지 반환해라.
풀이
내 풀이 코드 (defaultdict)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: freqs = collections.defaultdict(lambda : 0) for stone in stones: freqs[stone] += 1 count_jewels = 0 for jewel in jewels: count_jewels += freqs[jewel] return count_jewels
풀이 코드 (Counter)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: freqs = collections.Counter(stones) count_jewels = 0 for jewel in jewels : count_jewels += freqs[jewel] return count_jewels
풀이 코드 (Pythonic)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: return sum(stone in jewels for stone in stones)
퇴고
반응형