LeetCode 0771. Jewels and Stones Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0771. Jewels and Stones

Description

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

 

Constraints:

  • 1 <= jewels.length, stones.length <= 50
  • jewels and stones consist of only English letters.
  • All the characters of jewels are unique.

Solutions

Solution 1: Hash Table or Array

We can first use a hash table or array s to record all types of jewels. Then traverse all the stones, and if the current stone is a jewel, increment the answer by one.

Time complexity is O(m+n), and space complexity is O(|Σ|), where m and n are the lengths of the strings jewels and stones respectively, and Σ is the character set, which in this problem is the set of all uppercase and lowercase English letters.

PythonJavaC++GoTypeScriptRustJavaScriptC
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: s = set(jewels) return sum(c in s for c in stones)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !