Difficulty: 🟢 Easy
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"
.
Example 1:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ"
Output: 0
1 <= jewels.length, stones.length <= 50
jewels
andstones
consist of only English letters.- All the characters of
jewels
are unique.
Python 3
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
items = set([jewel for jewel in jewels])
return sum([1 for stone in stones if stone in items])
The given solution provides a straightforward approach to solving the problem.
Here is an overview of the solution:
- Create a set called
items
to store the unique types of stones that are jewels. Iterate through each character in thejewels
string and add it to the set. - Use a list comprehension to iterate through each character in the
stones
string. Check if the character is present in theitems
set. If it is, increment a counter by 1. - Return the counter, which represents the number of stones that are also jewels.
The time complexity for this solution is O(len(jewels) + len(stones)), as we iterate through the jewels
string to create the items
set and iterate through the stones
string to count the jewels.
The space complexity is O(len(jewels)) because we create a set to store the unique types of jewels.
The given solution provides a straightforward approach to count the number of stones that are also jewels. It creates a set of unique jewels and iterates through the stones, incrementing a counter for each stone that is present in the set. The solution runs in linear time and requires additional space to store the set of jewels.
NB: If you want to get community points please suggest solutions in other languages as merge requests.