LeetCode Solutions
771. Jewels and Stones
Time: $O(|\texttt{J}| + |\texttt{S}|)$ Space: $O(|\texttt{J}|)$
class Solution {
public:
int numJewelsInStones(string J, string S) {
int ans = 0;
unordered_set<char> jewels(begin(J), end(J));
for (const char s : S)
if (jewels.count(s))
++ans;
return ans;
}
};
class Solution {
public int numJewelsInStones(String J, String S) {
int ans = 0;
Set<Character> jewels = new HashSet<>();
for (char j : J.toCharArray())
jewels.add(j);
for (final char s : S.toCharArray())
if (jewels.contains(s))
++ans;
return ans;
}
}
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
jewels = set(J)
return sum(s in jewels for s in S)