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
Count how many stones are also jewels. Jewels are defined by a string of character types. Each stone character is compared against the jewel set. Use a hash set for O(1) lookups so the solution runs in linear time instead of checking each stone against every jewel character.
Build a lookup set from the jewel characters. Then iterate through each stone and check membership in the set. The problem distinguishes between uppercase and lowercase, so 'a' and 'A' are treated as different jewel types.
Time complexity is O(J + S), space complexity is O(J) where J is the jewels string length.
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.
