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.
Code in C++:
int numJewelsInStones(string J, string S) {
if(J.empty()) return 0;
int counter=0;
unordered_map<char, int> m;
for(char& stone: S) //count the occurrences of each character
m[stone]++;
for(char& jewel: J) {
if(m.find(jewel)!=m.end()) //increment counter for each character in `jewel`
counter+=m[jewel];
}
return counter;
}
注解:
1)用unordered_map统计S中字符出现的次数。。
2)将J依次与unordered_map对比,若是jewel,则加上该字符出现的次数。
Discuss地址:
https://discuss.leetcode.com/category/1726/jewels-and-stones