미소를뿌리는감자의 코딩
[leetcode 2024/02/07] 771. Jewels and Stones 본문
728x90
https://leetcode.com/problems/jewels-and-stones/description/
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
'코딩 테스트 > leetcode' 카테고리의 다른 글
[leetcode 2024/02/07] 347. Top K Frequent Elements - heapq.nlargest (1) | 2024.02.07 |
---|---|
[leetcode 2024/02/07] 3.Longest Substring Without Repeating Characters (0) | 2024.02.07 |
[leetcode 2024/02/06] 739. Daily Temperatures (1) | 2024.02.06 |
[leetcode 2024/02/06] 232. Implementing Queue using Stacks (1) | 2024.02.06 |
[leetcode 2024/02/06] 225. Implement Stack using Queues (0) | 2024.02.06 |