<--- 리트코드 771. Jewels and Stones --->

# 문제: J는 보석이며, S는 갖고 있는 돌이다. S에는 보석이 몇 개나 있을까? 대소문자는 구분한다.

 

입력

J = "aA", S = "aAAbbbb"

출력

3

 

 

# 풀이

1. 해시 테이블을 이용한 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def num_jewels_in_stones(J, S):
  freqs = {}
  count = 0
 
  for char in S:
    if char not in freqs:
      freqs[char] = 1
    else:
      freqs[char] += 1
 
  for char in J:
    if char in freqs:
      count += freqs[char]
 
  return count
 
= "aA"
= "aAAbbbb"
print(num_jewels_in_stones(J, S))
cs

 

2. defaultdict를 이용한 비교 생략 (존재하지 않는 키에 대해 디폴트를 Return)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import collections
 
def num_jewels_in_stones(J, S):
  freqs = collections.defaultdict(int)
  count = 0
 
  for char in S:
    freqs[char] += 1
 
  for char in J:
    count += freqs[char]
 
  return count
 
= "aA"
= "aAAbbbb"
print(num_jewels_in_stones(J, S))
cs

 

3. Counter로 계산 생략

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import collections
 
def num_jewels_in_stones(J, S):
  freqs = collections.Counter(S)
  count = 0
 
  for char in J:
    count += freqs[char]
  
  return count
 
= "aA"
= "aAAbbbb"
print(num_jewels_in_stones(J, S))
cs

 

4. 파이썬 다운 방식

1
2
3
4
5
6
def num_jewels_in_stones(J, S):
  return sum(s in J for s in S)
 
= "aA"
= "aAAbbbb"
print(num_jewels_in_stones(J, S))
cs