You are given two strings: jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in the string is a type of stone. Count how many of your stones are also jewels. Letters are case-sensitive, so 'a' is different from 'A'.
A hash set is the natural solution: add all jewel types to a set, then iterate through stones and count how many are in the set. This runs in O(n + m) time where n and m are the lengths of the strings. Without a hash set, you would need to check each stone against each jewel type in O(n * m) time.
This is one of the simplest hash set applications and is a common interview warm-up problem.
The problem may also be solved without a hash set using nested loops or regular expressions, but the hash set approach is the most efficient and the most readable.
Example Input & Output
All stones are jewels.
z != Z.
a and A are jewels.
Algorithm Flow

Solution Approach
Add all jewel chars to a set. Count stones that are in the set.
Time O(n+m), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int solution(String jewels, String stones) {
Set<Character> set = new HashSet<>();
for (char j : jewels.toCharArray()) set.add(j);
int count = 0;
for (char s : stones.toCharArray()) { if (set.contains(s)) count++; }
return count;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
