DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Edited on

2

LeetCode in Ruby: 771 Jewels and Stones

1 Line

This approach is based on Ruby’s String#count method. It takes the string j as the set of characters to count in the string s. This is the fastest and the simplest solution.

Time complexity: O(j.length+ s.length)

Extra memory: O(1)

Hash

def num_jewels_in_stones(j, s)
  stones = Hash.new 0
  s.each_char do |char|
    stones[char] += 1
  end

  sum = 0
  j.each_char do |char|
    sum += stones[char]
  end

  return sum
end

First, we iterate through the string s and create a hash called stones that uses the characters in s as keys and their occurrence as values. Then we go through each character of j and sum up their occurrences.

Time complexity: O(j.length+ s.length)

Extra memory: O(s.length)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
healeycodes profile image
Andrew Healey

Awesome solution. This is my favourite problem on LeetCode. It’s a simple introduction to hashmaps and why they’re amazing 👏

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay