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.
a
is considered a different type of stone from A
.Example:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
jewels
and stones
always non-empty?
jewels
and stones
contain only alphabetic characters and are case-sensitive.jewels
string?
jewels
string contains unique characters.jewels
string into a set for O(1) average-time complexity lookups.stones
and count how many of these characters are present in the jewels
set.def numJewelsInStones(jewels: str, stones: str) -> int:
jewels_set = set(jewels) # Step 1: Convert 'jewels' to a set
count = 0
for stone in stones: # Step 2: Iterate through 'stones'
if stone in jewels_set:
count += 1
return count
jewels
string.stones
string.For the input jewels = "aA"
and stones = "aAAbbbb"
jewels
to a set: {'a', 'A'}
stones
: count how many times characters ‘a’ and ‘A’ appear in stones
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?