Solving Problem 771 on Leetcode
This problem is called “Jewels and Stones” and the description is as follows:
“You’re given strings
jewels
representing the types of stones that are jewels, andstones
representing the stones you have. Each character instones
is a type of stone you have. You want to know how many of the stones you have are also jewels.Letters are case sensitive, so
"a"
is considered a different type of stone from"A"
.”
I worked on this problem in JavaScript and I began by doing some pseudo-coding. Initially I thought that I could compare the two strings and simply print out the “jewels” that were present in “stones”. However, this would be a problem because the problem asks for the total number of stones that are jewels. I then realized I would need to set up a hash table to compare stones and jewels and output a count.
I set up an empty object to the name “count” and a counter variable called “total”. I did a “for-of” loop where for each jewel, I added a 1 to the value. So the key value pairs in my object would be each jewel with the value of 1. Then I continued by doing another “for-of” loop, where in I asked if each stones existed inside the count object. If the name matched, it would add 1 to the total. Then, I returned the total!
var numJewelsInStones = function(jewels, stones) {
const count = {}
let total = 0
for(jewel of jewels){
count[jewel] = 1
}
for(stone of stones){
if (count[stone]) total += 1
}
return total
};
I’m still getting used to using hash tables and I’m sure this is quite a rudimentary solution but I’m excited to keep learning! Thank you for reading!