题目:
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
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
思路:
1.其实可以运用一次嵌套循环,来判断S中的字符串是否在J中,但是这样的话,复杂度太大。
2.结合C++的STL,set容器,先将J中的字符放进set中,再对S进行遍历,判断S中的字符是否在这个set中,用到find函数。
3.这个find函数比我们自己进行遍历的效率大很多。
4.我们应该熟练STL的用法。
代码:C++
class Solution {
public:
int numJewelsInStones(string J, string S) {
set<char> c;
for(int i = 0; i < J.size(); i++){
c.insert(J[i]);
}
int count = 0;
for(int i = 0; i < S.size(); i++){
if(c.find(S[i]) != c.end()){
count++;
}
}
return count;
}
};