LeetCode 771
1 min readMar 27, 2022
Using a hash map or a hash table is very prominent in the world of authentication, encryption, cryptography and much more! Hash tables help us encrypt information or data using key-value pairs.
In this article, it will be a brief overview of how to solve LeetCode 771.
The question is,
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"
.
My steps include:
- Create a new hash
- Initialize a counter equal to 0
- Set the hash with elements in the Jewels string.
- Iterate over the Stones string and determine if current iteration is in the Hash. If it is, increment a counter
- Return the counter
var numJewelsInStones = function(jewels, stones) {
//step 1
let hash = new Map()
//step 2
let count = 0
//step 3
for (let ele of jewels) {
hash.set(ele, ele)
}
//step 4
for (let i=0; i < stones.length; i++) {
if (hash.get(stones[i])) {
count++
}
}
//step 5
return count
}; let count = 0
for (let ele of jewels) {
hash.set(ele, ele)
}
for (let i=0; i < stones.length; i++) {
if (hash.get(stones[i])) {
count++
}
}
return count
};