Split the string J, representing the subset of all stones which are jewels, into a set where each element within that set represents a jewel. For each stone within the multiset S (represented as a string), determine whether that stone is indeed a jewel. Maintain a count of the number of stones within the multiset S which are jewels.
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
no_jewels = 0
jewels = set([jewel for jewel in J])
for stone in S:
if stone in jewels:
no_jewels += 1
return no_jewels
This can be rewritten to employ Python list comprehension:
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
jewels = set([jewel for jewel in J])
return len([1 for stone in S if stone in jewels])