Problem Statement:
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 different from "A".
Example:
Input: jewels = “aA”, stones = “aAAbbbb”
Output: 3
Input: jewels = “z”, stones = “ZZ”
Output: 0
Constraints:
- 1 ≤ jewels.length, stones.length ≤ 50
- jewels and stones consist of only English letters
- All characters in
jewelsare unique
Approach:
- Use a
Set(or hash set) to store all characters fromjewels. - Loop through each character in
stones. - Increment a counter for every character found in the
jewelsset.
Time and Space Complexity:
- Time Complexity: O(n + m), where
nis the length ofjewelsandmis the length ofstones. - Space Complexity: O(1) for storing unique characters from
jewels.
var numJewelsInStones = function(jewels, stones) {
let jSet = new Set(jewels);
let count = 0;
for (let c of stones) {
if (jSet.has(c)) count++;
}
return count;
};
int numJewelsInStones(char* jewels, char* stones) {
int count = 0;
for (int i = 0; stones[i] != '\0'; i++) {
for (int j = 0; jewels[j] != '\0'; j++) {
if (stones[i] == jewels[j]) {
count++;
break;
}
}
}
return count;
}
class Solution {
public:
int numJewelsInStones(string jewels, string stones) {
unordered_set jSet(jewels.begin(), jewels.end());
int count = 0;
for (char c : stones) {
if (jSet.count(c)) count++;
}
return count;
}
};
class Solution {
public int numJewelsInStones(String jewels, String stones) {
Set set = new HashSet<>();
for (char c : jewels.toCharArray()) {
set.add(c);
}
int count = 0;
for (char c : stones.toCharArray()) {
if (set.contains(c)) count++;
}
return count;
}
}
class Solution(object):
def numJewelsInStones(self, jewels, stones):
jset = set(jewels)
return sum(1 for c in stones if c in jset)
public class Solution {
public int NumJewelsInStones(string jewels, string stones) {
var set = new HashSet(jewels);
int count = 0;
foreach (char c in stones) {
if (set.Contains(c)) count++;
}
return count;
}
}
