771. Jewels and Stones Time: $O(|\texttt{J}| + |\texttt{S}|)$ Space: $O(|\texttt{J}|)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13class 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; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class 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; } } 1 2 3 4class Solution: def numJewelsInStones(self, J: str, S: str) -> int: jewels = set(J) return sum(s in jewels for s in S)