Jewels and Stones [Easy] — HashSet Membership
Advertisement
Problem Statement
jewels contains jewel types (distinct chars). Count how many stones in stones are jewels.
Input: jewels="aA", stones="aAAbbbb" → Output: 3
Solutions
C++
int numJewelsInStones(string j, string s) {
unordered_set<char> js(j.begin(),j.end());
int cnt=0; for(char c:s) cnt+=js.count(c);
return cnt;
}
Java
public int numJewelsInStones(String j, String s) {
Set<Character> js=new HashSet<>();
for(char c:j.toCharArray()) js.add(c);
int cnt=0; for(char c:s.toCharArray()) if(js.contains(c)) cnt++;
return cnt;
}
Python
def numJewelsInStones(jewels: str, stones: str) -> int:
js = set(jewels)
return sum(s in js for s in stones)
JavaScript
var numJewelsInStones = function(j, s) {
const js=new Set(j);
return [...s].filter(c=>js.has(c)).length;
};
Complexity
- Time: O(j+s), Space: O(j)
Advertisement