771. Jewels and Stones ¶ Time: $O(|\texttt{jewels}| + |\texttt{stones}|)$ Space: $O(|\texttt{jewels}|)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public: int numJewelsInStones(string jewels, string stones) { int ans = 0; unordered_set<char> jewelsSet(jewels.begin(), jewels.end()); for (const char stone : stones) if (jewelsSet.contains(stone)) ++ans; return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public int numJewelsInStones(String jewels, String stones) { int ans = 0; Set<Character> jewelsSet = jewels.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()); for (final char stone : stones.toCharArray()) if (jewelsSet.contains(stone)) ++ans; return ans; } } 1 2 3 4class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: jewelsSet = set(jewels) return sum(stone in jewelsSet for stone in stones)