LeetCode771-宝石与石头

LeetCode771-宝石与石头

暴力(O(mn))

枚举所有的字符进行比较

使用集合(O(m+n))

1
2
3
4
5
6
7
8
9
10
11
public int numJewelsInStones(String jewels, String stones) {
HashSet<Character> set = new HashSet<>();
int res = 0;
for (int i = 0; i < jewels.length(); i++) {
set.add(jewels.charAt(i));
}
for (int i = 0; i < stones.length(); i++) {
if (set.contains(stones.charAt(i))) res++;
}
return res;
}