771 보석과 돌
771 보석과 돌
문제
You’re given strings
jewels
representing the types of stones that are jewels, andstones
representing the stones you have. Each character instones
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의 타입을 나타낸다stones
: 내가 가진 돌을 나타내며,stones
의 각 문자는 내가 가진 돌의 타입을 나타낸다- 알고 싶은 것? 내가 가진 돌 중 얼마나 보석이 있는지
- 문자들은 대소문자를 구별한다
조건
- $1 \le jewels.length, stones.length \le 50$
- jewels and stones consist of only English letters.
- All the characters of jewels are unique.
예제
예제 1
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
예제 2
Input: jewels = "z", stones = "ZZ"
Output: 0
해결
1st
1.1 해결해야 할 사항
jewels
에 해당하는 문자가stones
에 얼마나 있는지 카운트
1.2 생각
jewels
의 각 문자는 유일하다고 하므로 중복은 고려하지 않아도 될 듯stones
를 잘라서 jewels에 해당하는 문자는 딕셔너리에 카운트해서 담아서 카운트?- Counter를 쓰면?
1.3 구현
1.3.1 dictionary 사용
def first(self, jewels: str, stones: str) -> int:
# https://docs.python.org/ko/3/library/stdtypes.html?highlight=dict#dict
jewels_dict = {}
ans = 0
for jewel in jewels:
jewels_dict[jewel] = True
for stone in stones:
if stone in jewels_dict:
ans += 1
return ans
Runtime: 32 ms, faster than 63.11% of Python3 online submissions for Jewels and Stones. Memory Usage: 14.2 MB, less than 76.02% of Python3 online submissions for Jewels and Stones.
1.3.2 Couter 사용
def second(self, jewels: str, stones: str) -> int:
# https://docs.python.org/ko/3/library/collections.html?highlight=counter#collections.Counter
c = Counter(stones)
ans = 0
for jewel in jewels:
if jewel in c:
ans += c[jewel]
return ans
Runtime: 36 ms, faster than 21.95% of Python3 online submissions for Jewels and Stones. Memory Usage: 14.3 MB, less than 48.17% of Python3 online submissions for Jewels and Stones.
1.3.3 문자열 그대로 사용
def third(self, jewels: str, stones: str) -> int:
ans = 0
for stone in stones:
if stone in jewels:
ans += 1
return ans
Runtime: 32 ms, faster than 63.11% of Python3 online submissions for Jewels and Stones. Memory Usage: 14.1 MB, less than 91.67% of Python3 online submissions for Jewels and Stones.
1.3.4 문자열 그대로 사용2
- 리트 코드에 답으로 올라가 있는 코드 중 가장 빠른 코드로 기록된 걸로 테스트
def fourth(self, jewels: str, stones: str) -> int:
count = 0
for c in jewels:
if c in stones:
count += stones.count(c)
return count
Runtime: 28 ms, faster than 85.95% of Python3 online submissions for Jewels and Stones. Memory Usage: 14.4 MB, less than 13.91% of Python3 online submissions for Jewels and Stones.