Jewels And Stones - leetcode(771)

llama·2022년 3월 16일

알고리즘

목록 보기
11/16
post-thumbnail

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:
        # stone을 Counter로 중복되는 요소를 합쳐서 카운팅한다.
        res = collections.Counter(stones)

        # jewels의 보석을 빼서, res[key]로 사용하면 카운팅된 개수가 나오기 때문에 sum()으로 리스트 요소를 합치면 보석의 갯수를 찾을 수 있다.
        return sum([res[k] for k in jewels])

sol = Solution()

print(sol.numJewelsInStones(preJewels, preStones))

📌 코드 풀이

  1. collections의 Counter를 이용하여 같은 원석의 개수를 카운팅 한다.
  2. 리스트에서 for문을 이용하여 jewels의 문자들을 key로 이용하여 1번에서 만든 카운터 딕셔너리의 키값으로 이용한다.
  3. 리스트에 원석에서 보석에 해당하는 개수가 들어있기 때문에 sum()을 이용해 요소의 합을 반환하면 된다.

leetcode

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

profile
요리사에서 프론트엔드 개발자를 준비하는중 입니다.

0개의 댓글