[LeetCode] – Jewels and Stones [Easy]
2018 Dec 3rd
The challenge I am going to explain is the Jewels and Stones challenge, which, by the way, is a concise one. The description of the problem is as follows:
You’re given strings
Jrepresenting the types of stones that are jewels, andSrepresenting the stones you have. Each character inSis a type of stone you have. You want to know how many of the stones you have are also jewels.The letters in
Jare guaranteed distinct, and all characters inJandSare letters. Letters are case sensitive, so"a"is considered a different type of stone from"A".Example 1:
Input: J = "aA", S = "aAAbbbb" Output: 3Example 2:
Input: J = "z", S = "ZZ" Output: 0
Thus, each jewel from the String J is compared with each stone I have. If the jewel matches the stone I have, it means that I have a jewel. After all the stones are compared, the function returns the number of jewels I have.
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
'''
J - types of stones that are jewels (J distinct)
S - stones you have
Each char in S is a type of stone I have
'''
# take each stone from J an check if it is found in S
return sum(stone in J for stone in S)
The following line:
return sum(stone in J for stone in S)
Can be restructured as follows:
count = 0
for jewel in J:
for stone in S:
if jewel == stone:
count += 1
return count
For the moment, I prefer the second solution because it is easier for a beginner like me to understand what is happening. Nonetheless, the first solution is more beautiful and quicker.
The statistics for the first code are:
