
문제
https://leetcode.com/problems/jewels-and-stones/
Jewels and Stones - LeetCode
Can you solve this real interview question? 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 kno
leetcode.com
주어진 문자열(S)에 문자열(J)이 몇 개 있는지 찾는 문제다. (대소문자 구분)
예시
Example 1:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ"
Output: 0
풀이
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
# jewels = set(jewels)
count = 0
for s in stones:
if s in jewels:
count += 1
return count
- stones에 있는 문자가 jewels에 있는 지 확인 후 count를 1씩 더해준다.
- set으로 변환하여 중복된 원소를 제거하면 탐색 속도를 올릴 수 있다. (이 문제는 입력 크기가 작아 큰 차이를 보이지 않음.)
참조 : 박상길, 파이썬 알고리즘 인터뷰 https://github.com/onlybooks/algorithm-interview
'알고리즘' 카테고리의 다른 글
| [리트코드(LeetCode)] 215번 Kth Largest Element in an Array (1) | 2024.01.06 |
|---|---|
| [백준(BOJ)] 17219번 비밀번호 찾기 (2) | 2024.01.06 |
| [리트코드(LeetCode)] 225번, 232번 Stack, Queue (1) | 2024.01.05 |
| [리트코드(LeetCode)] 561번 Array Partition (0) | 2024.01.04 |
| [리트코드(LeetCode)] 15번 3Sum (2) | 2024.01.04 |