소프트웨어에 대한 모든 것

LeetCode 풀기 - 771. Jewels and Stones 본문

알고리즘/LeetCode

LeetCode 풀기 - 771. Jewels and Stones

앤테바 2021. 10. 29. 09:43
반응형

771. 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".

 

 

솔루션1)

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        # stones를 dict로 구성
        # key = jewel, value = jewel count
        stone_dict = defaultdict(int)
        for stone in stones:
            stone_dict[stone] += 1
        
        jewel_count = 0
        for jewel in jewels:
            jewel_count += stone_dict[jewel]
        return jewel_count

솔루션2)

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        # stones를 dict로 구성
        # key = jewel, value = jewel count
        stone_dict = defaultdict(int)
        for stone in stones:
            stone_dict[stone] += 1
        
        return sum(stone_dict[jewel] for jewel in jewels)

솔루션3)

  • 정의된 문자열에서 해당 문자가 몇 번 존재하는지 count 함수를 사용하는 풀이 방법
class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
         return sum(map(stones.count, jewels))

 

반응형
Comments