【题目】
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"
.
两个集合A、B。A中是石头,B中是宝石。通过比对返回石头A中是宝石的个数。
【思路】
string转换外char数组,把原始数据存在HashSet中,通过比较键值,是否contains了B中的元素来控制ans++
【代码】
class Solution {
public int numJewelsInStones(String J, String S) {
char[] js=J.toCharArray();
char[] ss=S.toCharArray();
Set data=new HashSet();
int ans=;
//加入数据
for(char j:js){
data.add(j);}
//遍历是否相等
for(char s:ss){
if(data.contains(s))
ans++;
}
return ans;
}
}
【参考】