Jewels and Stones

easy hash map string

Problem

Given a string jewels of distinct jewel types and a string stones, return the number of stones that are jewels.

Inputjewels = "aA", stones = "aAAbbbb"
Output3
Stones 'a', 'A', 'A' are jewels; the four 'b's are not.

def num_jewels_in_stones(jewels, stones):
    j = set(jewels)
    count = 0
    for c in stones:
        if c in j:
            count += 1
    return count
function numJewelsInStones(jewels, stones) {
  const j = new Set(jewels);
  let count = 0;
  for (const c of stones) {
    if (j.has(c)) count++;
  }
  return count;
}
class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        Set<Character> j = new HashSet<>();
        for (char c : jewels.toCharArray()) j.add(c);
        int count = 0;
        for (char c : stones.toCharArray()) {
            if (j.contains(c)) count++;
        }
        return count;
    }
}
class Solution {
public:
    int numJewelsInStones(string jewels, string stones) {
        unordered_set<char> j(jewels.begin(), jewels.end());
        int count = 0;
        for (char c : stones) {
            if (j.count(c)) count++;
        }
        return count;
    }
};
Time: O(|J| + |S|) Space: O(|J|)