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".

Examples

Example 1

1
2
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3

Example 2

1
2
Input: jewels = "z", stones = "ZZ"
Output: 0

Constraints

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

Solution

Method 1 – Hash Set Lookup

Intuition

We want to count how many stones are jewels. By storing all jewel types in a set, we can check each stone in constant time.

Approach

  1. Store all characters from jewels in a set for fast lookup.
  2. Iterate through each character in stones.
  3. For each stone, if it is in the set, increment the count.
  4. Return the count.

Code

1
2
3
4
5
6
7
8
9
class Solution {
public:
    int numJewelsInStones(string jewels, string stones) {
        unordered_set<char> s(jewels.begin(), jewels.end());
        int ans = 0;
        for (char c : stones) if (s.count(c)) ++ans;
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func numJewelsInStones(jewels, stones string) int {
    s := map[rune]struct{}{}
    for _, c := range jewels {
        s[c] = struct{}{}
    }
    ans := 0
    for _, c := range stones {
        if _, ok := s[c]; ok {
            ans++
        }
    }
    return ans
}
1
2
3
4
5
6
7
8
9
class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        Set<Character> s = new HashSet<>();
        for (char c : jewels.toCharArray()) s.add(c);
        int ans = 0;
        for (char c : stones.toCharArray()) if (s.contains(c)) ans++;
        return ans;
    }
}
1
2
3
4
5
6
class Solution {
    fun numJewelsInStones(jewels: String, stones: String): Int {
        val s = jewels.toSet()
        return stones.count { it in s }
    }
}
1
2
3
def num_jewels_in_stones(jewels: str, stones: str) -> int:
    s = set(jewels)
    return sum(c in s for c in stones)
1
2
3
4
5
use std::collections::HashSet;
fn num_jewels_in_stones(jewels: &str, stones: &str) -> i32 {
    let s: HashSet<char> = jewels.chars().collect();
    stones.chars().filter(|c| s.contains(c)).count() as i32
}
1
2
3
4
5
6
7
8
class Solution {
  numJewelsInStones(jewels: string, stones: string): number {
    const s = new Set(jewels);
    let ans = 0;
    for (const c of stones) if (s.has(c)) ans++;
    return ans;
  }
}

Complexity

  • ⏰ Time complexity: O(m + n) — m is the length of jewels, n is the length of stones.
  • 🧺 Space complexity: O(m) — For the set of jewels.