Problem Description
Given two strings jewels and stones, count how many stones you have that are also jewels. Each character in stones represents a type of stone, and the letters in jewels indicate which stones are jewels. Note that letters are case sensitive.
Key Insights
- Use a hash set to store the jewels for O(1) membership checking.
- Iterate over every stone and check if it is in the jewels set.
- Count and return the number of stones that are jewels.
Space and Time Complexity
Time Complexity: O(n + m), where n is the length of stones and m is the length of jewels. Space Complexity: O(m), for storing the jewels in a set.
Solution
The solution involves using a hash set data structure to store all the jewels so that each lookup during the iteration over stones is constant time. Then, iterate over each stone in the stones string; if the stone exists in the hash set, increment a counter. Finally, return the counter. This approach efficiently checks membership and solves the problem with linear time complexity relative to the input sizes.