From dafb096e656977f8c4b2c975c923337c475ba32e Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Thu, 25 Mar 2021 14:38:13 -0700 Subject: [PATCH] Add solution using hash --- data_structures/arrays/jewels_and_stones.rb | 36 +++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/data_structures/arrays/jewels_and_stones.rb b/data_structures/arrays/jewels_and_stones.rb index 881c7c5..a777534 100644 --- a/data_structures/arrays/jewels_and_stones.rb +++ b/data_structures/arrays/jewels_and_stones.rb @@ -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")