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
统计字符串J中的每一个字符在S中出现的总次数之和
C++(13ms):
1 class Solution { 2 public: 3 int numJewelsInStones(string J, string S) { 4 int res = 0 ; 5 for(char c1 : J){ 6 for(char c2 : S){ 7 if (c1 == c2) 8 res++ ; 9 } 10 } 11 return res ; 12 } 13 };
C++(14ms):
1 class Solution { 2 public: 3 int numJewelsInStones(string J, string S) { 4 int res = 0 ; 5 unordered_set<char> setJ(J.begin() , J.end()) ; 6 for(char c : S){ 7 if (setJ.count(c)) 8 res++ ; 9 } 10 return res ; 11 } 12 };