LeetCode 771. Jewels and Stones
考点 | 难度 |
---|---|
Hash Table | Easy |
题目
You’re given strings jewels
representing the types of stones that are jewels, and stones
representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so “a” is considered a different type of stone from “A”.
思路
建一个hash set存储所有jewel种类,查stones
里的每一位是不是在hash set里面。
答案
public int numJewelsInStones(String jewels, String stones) {
HashSet<Character> j = new HashSet<>();
for(int i=0; i<jewels.length(); i++){
char c = jewels.charAt(i);
if(!j.contains(c)){
j.add(c);
}
}
int res=0;
for(int i=0; i<stones.length(); i++){
char c = stones.charAt(i);
if(j.contains(c)){
res++;
}
}
return res;
}