https://leetcode.com/problems/jewels-and-stones/
You're given strings
jewelsrepersenting the types of stones that are jewels, andstonesrepersenting the stones you have. Each character instonesis 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".
stones 문자열을 순회하며 jewels 문자열에 포함된 문자인지 아닌지를 체크하여 count 변수값을 더해주는 방식으로 코드를 작성했다.
stones 문자열에 포함된 문자를 카운트해주기 위해 collections 모듈에 Counter() 객체를 사용하였다.
이 후, jewels 문자열을 순회하며 카운트해준 값을 더해주었다.
class Solution:
# collections.Counter() 사용
def numJewelsInStones(self, jewels: str, stones: str) -> int:
stones_table = collections.Counter(stones)
count = 0
for jewel in jewels:
count += stones_table[jewel]
return count
class Solution:
# in 사용
def numJewelsInStones(self, jewels: str, stones: str) -> int:
count = 0
for stone in stones:
if stone in jewels:
count += 1
return count
collections.Counter() 의 경우, 다음과 같이 구현할 수 있다. 전체 리스트를 한 번 순회하므로 시간복잡도는 이다.list = [...]
dict = {...}
for item in list:
if item not in dict:
dict[item] = 1
else:
dict[item] += 1
리스트의 경우, stones 를 돌면서 매 루프마다 jewels 에서 in을 사용하므로 총 시간복잡도는 이 된다.