Jewels and Stones in Python


Suppose we have a string J that indicates some letters that are considered as Jewel, and another string S, that represents some stones that we have. Our task is to find how many of stones in S is also jewel. The letters in J and S are case sensitive. So if the J = “aZc”, and S = “catTableZebraPicnic” then there are 7 jewels.

To solve this we will convert the string into a list of characters. If the character in J present in S, then increase the count.

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def numJewelsInStones(self, J, S):
      """
      :type J: str
      :type S: str
      :rtype: int
      """
      jewels = {}
      for i in J:
         jewels[i] = 1
      number = 0
      for i in S:
         if i in jewels:
            number+=1
      return number

Input

"aZc"
"catTableZebraPicnic"

Output

7
raja
Published on 16-Jan-2020 11:08:13
Advertisements