05 August 2008
You’re given strings
representing the types of stones that are jewels, and 1
J
representing the stones you have. Each character in 1
S
is a type of stone you have. You want to know how many of the stones you have are also jewels.1
S
The letters in
are guaranteed distinct, and all characters in 1
J
and 1
J
are letters. Letters are case sensitive, so 1
S
is considered a different type of stone from 1
"a"
.1
"A"
Example 1:
1
2
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
1
2
Input: J = "z", S = "ZZ"
Output: 0
Note:
1
S
and 1
J
will consist of letters and have length at most 50.1
J
are distinct.这道题J中的字符全是珠宝分类,没有重复,S中的字符是石头或者珠宝,找出S中所有是珠宝的字符。暴力搜索就是把J中字符分别拿到S中去对比下,match一次就+1;decent一点的做法则是用hashset把J中的字符装入(因为没重复),然后把S中的字符分别来看是否存在。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int numJewelsInStones(String J, String S) {
int result = 0;
Set<Character> jset = new HashSet<>();
for (char j : J.toCharArray()) {
jset.add(j);
}
for (char s : S.toCharArray()) {
if (jset.contains(s)) {
result++;
}
}
return result;
}
}