Jewels and Stones in Python

PythonServer Side ProgrammingProgramming

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.


Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def numJewelsInStones(self, J, S):
      jewels = {}
      for i in J:
         jewels[i] = 1
      number = 0
      for i in S:
         if i in jewels:
      return number
ob1 = Solution()
print(ob1.numJewelsInStones("aZc", "catTableZebraPicnic"))




Published on 16-Jan-2020 15:38:13