# 771. Jewels and Stones

You’re given strings `J` representing the types of stones that are jewels, and `S` representing the stones you have.  Each character in `S`is a type of stone you have.  You want to know how many of the stones you have are also jewels.

The letters in `J` are guaranteed distinct, and all characters in `J` and `S` are letters. Letters are case sensitive, so `"a"` is considered a different type of stone from `"A"`.

Example 1:

``````Input: J = "aA", S = "aAAbbbb"
Output: 3
``````

Example 2:

``````Input: J = "z", S = "ZZ"
Output: 0
``````

Note:

• `S` and `J` will consist of letters and have length at most 50.
• The characters in `J` are distinct.

``````class Solution {
public:
int numJewelsInStones(string J, string S) {
int res = 0;
for (char s : S) {
for (char j : J) {
if (s == j) {
++res; break;
}
}
}
return res;
}
};
``````

``````class Solution {
public:
int numJewelsInStones(string J, string S) {
int res = 0;
unordered_set<char> s;
for (char c : J) s.insert(c);
for (char c : S) {
if (s.count(c)) ++res;
}
return res;
}
};
``````

https://leetcode.com/problems/jewels-and-stones/solution/

https://leetcode.com/problems/jewels-and-stones/discuss/113553/C++JavaPython-Easy-and-Concise-Solution-O(M+N)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation