Categories:

Tags:



Problem

You’re given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones 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".

Constraints

  • 1 <= jewels.length, stones.length <= 50
  • jewels and stones consist of only English letters.
  • All the characters of jewels are unique.

Solution

The problem Jewels and Stones can be solved by storing information on all jewels into a hash map and checking if each stone is present in it.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    int numJewelsInStones(string jewels, string stones)
    {
        unordered_set<char> hashmap;
        for (char &jewel : jewels)
            hashmap.insert(jewel);

        int ret = 0;
        for (char &stone : stones)
            if (hashmap.find(stone) != hashmap.end())
                ret += 1;

        return ret;
    }
};