题目
一个字符串 jewels 代表宝石的类型,另有一个字符串 stones 代表石头。 stones 中每个字符代表了一种你拥有的石头的类型,jewels中每个字符串代表你拥有的宝石,请判断石头中宝石的个数
2.分析
我们使用HashSet用于存放宝石的类型,我们遍历jewels,判断每个字符是否是宝石。
3.代码
class Solution {
public int numJewelsInStones(String jewels, String stones) {
Set<Character> set = new HashSet<>();
for(int i = 0; i < jewels.length(); i++) {
char tmp = jewels.charAt(i);
set.add(tmp);
}
int count = 0;
for(int i = 0; i < stones.length(); i++) {
char tmp = stones.charAt(i);
if(set.contains(tmp)) {
count++;
}
}
return count;
}
}