알고리즘

[리트코드(LeetCode)] 771번 Jewels and Stones

욘아리 2024. 1. 5. 23:08

문제

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

 

Jewels and Stones - LeetCode

Can you solve this real interview question? 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 kno

leetcode.com

주어진 문자열(S)에 문자열(J)이 몇 개 있는지 찾는 문제다. (대소문자 구분)

예시

Example 1:

Input: jewels = "aA", stones = "aAAbbbb"
Output: 3

 

Example 2:

Input: jewels = "z", stones = "ZZ"
Output: 0

풀이

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
#       jewels = set(jewels)
        count = 0
        for s in stones:
            if s in jewels:
                count += 1
        return count

 

- stones에 있는 문자가 jewels에 있는 지 확인 후 count를 1씩 더해준다.

- set으로 변환하여 중복된 원소를 제거하면 탐색 속도를 올릴 수 있다. (이 문제는 입력 크기가 작아 큰 차이를 보이지 않음.)

 

참조 : 박상길, 파이썬 알고리즘 인터뷰  https://github.com/onlybooks/algorithm-interview