498/670

498. Jewels and Stones

Easy

You are given two strings. jewels lists every character that counts as a jewel — all of its characters are distinct. stones describes the stones you are carrying, one character per stone.

Return the number of stones that are jewels, i.e. how many positions i satisfy stones[i] ∈ jewels. Duplicate stones each count separately.

Matching is case-sensitive: 'a' and 'A' are different kinds of stone.

Example 1:

Input: jewels = "aA", stones = "aAAbbbb"

Output: 3

Explanation: The jewel types are 'a' and 'A'. Among the stones, one 'a' and two 'A's match, so 3 stones are jewels; the four 'b's are not.

Example 2:

Input: jewels = "z", stones = "ZZ"

Output: 0

Explanation: Comparison is case-sensitive, so uppercase 'Z' stones do not match the lowercase jewel 'z'.

Constraints:

  • 1 ≤ jewels.length ≤ 50
  • 1 ≤ stones.length ≤ 10⁴
  • jewels and stones consist of English letters only (a-z, A-Z)
  • All characters of jewels are distinct.

Hints:

Every stone poses the same yes/no question: does this character occur in jewels? You can answer it by scanning jewels each time, but that repeats work.

Build a hash set of the jewel characters once. Each stone then costs one O(1) membership check, so the whole count is a single pass over stones.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: jewels = "aA", stones = "aAAbbbb"

Expected output: 3