LeetCode Easy 문제인 'Jewels and Stones' 문제를 풀어보았다.
https://leetcode.com/problems/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".
jewels에 있는 글자와 stones에 있는 글자를 하나하나 비교하여(이중 for문) 비교하고, 같으면 cnt++하여 cnt를 정답으로 리턴했다.
class Solution:
def numJewelsInStones(self, jewels, stones):
cnt = 0
for i in jewels:
for j in stones:
if i == j:
cnt += 1
return cnt
딕셔너리를 사용해서 풀어보려고 했는데, 딕셔너리끼리 비교하는 부분에서 막혀서 못풀었다.
class Solution:
def numJewelsInStones(self, jewels, stones):
stones_dict = {}
jewels_dict = {}
for stone in stones:
# {'a': 1, 'A': 2, 'b': 4}
stones_dict[stone] = stones.count(stone)
# {'a': 1, 'A': 1}
for jewel in jewels:
jewels_dict[jewel] = jewels.count(jewel)
딕셔너리를 이용해서 풀었다. 이전 풀이에서 실패한 이유는 다음과 같다.
class Solution:
def numJewelsInStones(self, jewels, stones):
stones_dict = {}
jewels_dict = {}
have_dict = {}
for stone in stones:
stones_dict[stone] = stones.count(stone)
for jewel in jewels:
jewels_dict[jewel] = jewels.count(jewel)
for jewel in jewels:
have_dict[jewel] = stones.count(jewel)
return sum(have_dict.values())
이렇게 간단한 풀이도 있었다.
https://deep-learning-study.tistory.com/356
class Solution:
def numJewelsInStones(self, jewels, stones: str) -> int:
return sum(s in jewels for s in stones)