미소를뿌리는감자의 코딩

[leetcode 2024/02/07] 771. Jewels and Stones 본문

코딩 테스트/leetcode

[leetcode 2024/02/07] 771. Jewels and Stones

미뿌감 2024. 2. 7. 15:32
728x90

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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. 접근 방법

jewels = "aA", stones = "aAAbbbb" 일 때, aA가 stones에 몇개있냐?! 를 물어보는 문제이다.

우선, stones의 값을 for in 으로 하나씩 돌기 시작했다.

선언 된 dictionary 마다 dict_jewel[s] +=1 을 해서, 문자마다 개수를 세주었다.

즉, stones의 경우 다음과 같이 dictionary에 저장되게 된다.

{'a': 1, 'A': 2, 'b': 4})

 

이후 jewels 문자열을 for in 으로 하나씩 돌면서, dictionary value를 더해주었다.

 

이번에 python의 dictionary 가 hash 를 이용한다는 점을 알게되었다. 

이전에는 알지 못하고 dictionary를 썼었는데 그 점을 알고나니 ditionary를 애용해야겠다는 생각이 들었다.

 

2. 코드

from collections import defaultdict

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        dict_jewel = defaultdict(int)
        result = 0
        for s in stones:
            dict_jewel[s] += 1
        #print(dict_jewel)
        for j in jewels:
            result += dict_jewel[j]
        return result

solution = Solution()
print(solution.numJewelsInStones("aA", "aAAbbbb"))
728x90