mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-13 08:01:03 +01:00
Add solution using hash
This commit is contained in:
parent
7c6b226eac
commit
dafb096e65
1 changed files with 36 additions and 0 deletions
|
@ -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")
|
||||
|
|
Loading…
Reference in a new issue