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.
題目大意:
??給定兩個字符串J
和S
躁倒,問J
中的字符在S
中一共出現(xiàn)過幾次
??并且J
的值是唯一的
解題思路:
??因為J
的值是唯一的炼列,可根據(jù)J
構(gòu)建set,然后遍歷S
??時間復(fù)雜度O(s * j),s和j分別為S
和J
的大小
??空間復(fù)雜度
解題代碼:
class Solution {
public:
int numJewelsInStones(string J, string S) {
int result =0;
set<char>jewels;
for(size_t i = 0; i < J.size(); ++i)
jewels.insert(J[i]);
for(size_t i = 0; i < S.size(); ++i)
if(jewels.count(S[i]))
result++;
return result;
}
};