Add solution using hash

This commit is contained in:
Jessica Kwok 2021-03-25 14:38:13 -07:00
parent 7c6b226eac
commit dafb096e65

View file

@ -44,6 +44,42 @@ def find_jewels(jewels, stones)
result
end
puts find_jewels("aA", "aAAbbbb")
# => 3
puts find_jewels("z", "ZZ")
# => 0
#
# Approach 2: Hash
#
# Time Complexity: O(n)
#
def find_jewels(jewels, stones)
jewels_array = jewels.split('')
stones_array = stones.split('')
result_hash = {}
result = 0
stones_array.each do |stone|
if result_hash[stone]
result_hash[stone] += 1
else
result_hash[stone] = 1
end
end
jewels_array.each do |jewel|
if result_hash[jewel]
result += result_hash[jewel]
else
result
end
end
result
end
puts find_jewels("aA", "aAAbbbb")
# => 3
puts find_jewels("z", "ZZ")