m1ndy5's coding blog

LeetCode 771. Jewels and Stones with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 771. Jewels and Stones with Python

정민됴 2024. 1. 4. 19:57

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

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        jewels_dic = {jewel: 0 for jewel in jewels}

        for stone in stones:
            if stone in jewels_dic:
                jewels_dic[stone] += 1

        return sum(jewels_dic.values())

stones에 jewels가 몇개 나왔는지 dictionary에 저장하고 더하는 식으로 풀었는데 아주 쿨한 코드를 발견했다.

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        return sum(s in jewels for s in stones)

이렇게도 풀 수 있구나를 알았다 ㄷㄷㄷ 굳!