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

 

Jewels and Stones - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


풀이 과정

보석 문자열과 돌 문자열을 받아서 돌 문자열 안에 보석이 몇 개 들어있는지 구하는 문제이다.

 

보석 문자를 딕셔너리에 저장하고, 돌 문자열을 읽으면서 딕셔너리에 있는 문자면 정답 변수를 1씩 늘려주는 방법으로 풀이하였다.

 

52개의 0으로 초기화 된 리스트를 선언 후, 보석 문자를 읽으면서 해당하는 index의 원소를 1로 바꿔주고, 다시 돌 문자를 읽으면서 배열 index 확인하며 정답 변수를 1씩 늘리는 방법으로도 해결이 가능하다.


소스 코드

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        diction = collections.defaultdict(int)
        answer = 0
        for letter in jewels:
            diction[letter] = 1
        for letter in stones:
            if diction[letter] == 1:
                answer += 1
        return answer

+ Recent posts