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
中一共出现过几次
并且J
的值是唯一的
解题思路:
因为J
的值是唯一的,可根据J
构建set,然后遍历S
时间复杂度O(s * j),s和j分别为S
和J
的大小
空间复杂度
解题代码:
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;
}
};
网友评论