771 보석과 돌

문제

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”.

조건

예제

예제 1

Input: jewels = "aA", stones = "aAAbbbb"
Output: 3

예제 2

Input: jewels = "z", stones = "ZZ"
Output: 0

해결

1st

1.1 해결해야 할 사항

1.2 생각

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.